从内部块调用块

时间:2014-04-04 08:20:27

标签: objective-c

在Objective-c中,我们声明了一个完成块,它充当Web请求的回调。

如果请求失败,那么我希望能够在完成块内再次调用该函数。当我这样做时,由于没有完全定义块,我得到EXC_BAD_ACCESS

这很烦人,因为在Java中我可以用听众来做这件事。

是否可以从内部调用完成块?

感谢。

以下代码引发错误,我该如何解决?

CustomErrorBlock errorBlock = ^(NSError *error) {

    _processing = NO;
    loadingView.hidden = YES;

    self.infoText.hidden = NO;
    self.infoText.text = @"A network connection error has occurred.";
};


CustomCompletionBlock completionBlock = ^(NSData *data){

    if(![self processGetTransactions:data withDict:updateDict]) {

        [webClient getTransactions:updateDict WithCompletionBlock:completionBlock andErrorBlock:errorBlock];
    }
};
[webClient getTransactions:updateDict WithCompletionBlock:completionBlock andErrorBlock:errorBlock];

1 个答案:

答案 0 :(得分:0)

应该能够通过使用__block来停止EXC_BAD_ACCESS崩溃,这告诉编译器必须以特殊方式处理它,并且__weak会使对象不能保持强大。

__block CustomErrorBlock errorBlock = ^(NSError *error) {

    _processing = NO;
    loadingView.hidden = YES;

    self.infoText.hidden = NO;
    self.infoText.text = @"A network connection error has occurred.";
};


__block CustomCompletionBlock completionBlock = ^(NSData *data) {

    if(![self processGetTransactions:data withDict:updateDict]) {
        __weak CustomCompletionBlock weakCompletionBlock = completionBlock; // Note seems to always have retain cycle

        [webClient getTransactions:updateDict WithCompletionBlock:weakCompletionBlock andErrorBlock:errorBlock];
    }
};

    [webClient getTransactions:updateDict WithCompletionBlock:completionBlock andErrorBlock:errorBlock];

注意:弱对象仍会显示有关对象由于某种原因而变强的消息,但它的工作没有任何问题。