使用块作为回调处理程序

时间:2013-10-11 04:55:10

标签: ios objective-c block

我想使用块作为回调处理程序,但我不确定我在做什么是正确的,因为我的应用程序正在崩溃。 这就是我在做的事情:

在我的FirstViewController中,我调用类FirstModel的方法从服务器获取数据,如下所示:

//In FirstViewController.m
[aFirstModelObj retreiveDataWithCallBackHandler:^(NSDictionary *responseDict){

   //Data is received so we can proceed...
}];

//In FirstModel.m
typedef void(^newBlock)(NSDictionary *);
    newBlock theBlock;

-(void)retreiveDataWithCallBackHandler:(void(^)(NSDictionary *))aBlock
{
    //Saving "aBlock" for further use..
    theBlock = aBlock;

    //Server Processor will retrieve data using URL asynchronously,
   //initializing ServerProcessor object and providing FirstModel its delegate,so that when data is received in ServerProcessor class FirstModel's receivedResponse method will get called.

    serverProcessorObj.delegate = self;

}

-(void)receivedResponse:(NSDictionary *)responseDict
{
   //once data is received call block,
   theBlock(responseDict);
}

我的应用程序崩溃了,因为我失去了委托。当我从ServerProcessor调用[delegate receivedResponse:response]时,它说错误访问。谁能说出我做错了什么?

提前致谢!

2 个答案:

答案 0 :(得分:0)

除了检查块不是nil(根据评论),也许它与某些事情有关:

上述方法只允许您一次处理一个异步请求。您是否尝试处理并发请求?后续请求将覆盖先前请求的块。这可能会导致问题。

如果您需要支持并发请求,则需要为当前正在运行的请求保留每个块,以便在完成请求后调用。

如果您传入的是对象,例如:

retreiveDataForCustomer:(Customer*)customer onSuccess:(void (^)(NSDictionary*))success

。 。 。那么我建议在客户对象上创建一个属性或associative reference来保留块。但是,由于您的调用没有参数,您必须找到另一种方法来跟踪哪个块与哪个委托调用一起使用。

答案 1 :(得分:0)

我已经更正了您的代码。

-(void)retreiveDataWithCallBackHandler:(void(^)(NSDictionary *))aBlock
{
    //Saving "aBlock" for further use..
    theBlock = Block_copy(aBlock);

    //Server Processor will retrieve data using URL asynchronously,
    //initializing ServerProcessor object and providing FirstModel its delegate,so that when data is received in ServerProcessor class FirstModel's receivedResponse method will get called.

    serverProcessorObj.delegate = self;

}

-(void)receivedResponse:(NSDictionary *)responseDict
{
   //once data is received call block,
   if (theBlock)
       theBlock(responseDict);
}