0

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

在我的 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] 时,它说 exc bad access。谁能告诉我做错了什么?

提前致谢!

4

2 回答 2

0

除了检查该块是否不为零(根据评论),也许它与以下内容有关:

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

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

如果您要传递对象,例如:

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

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

于 2013-10-11T07:54:20.667 回答
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);
}
于 2013-11-22T09:40:59.667 回答