在Objective-C中使用块递归 [英] Recursion with blocks in objective-c

查看:187
本文介绍了在Objective-C中使用块递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当执行涉及Objective-C块的递归时,我在iOS应用程序中收到EXC_BAD_ACCESS信号.这是简化的代码:

- (void)problematicMethod:(FriendInfo*)friendInfo onComplete:(void(^)(NSString*))onComplete1 {

[self doSomethingWithFriend:friendInfo onComplete:^(Response* response) {
    switch (response.status) {
        case IS_OK:
            onComplete1(message);
            break;

        case ISNT_OK:
            // Recursively calls the method until a different response is received 
            [self problematicMethod:friendInfo onComplete:onComplete1];
            break;          

        default:
            break;
    }
}];
}

因此,基本上,在此简化版本中, problematicMethod 调用了 doSomethingWithFriend:onComplete:.当该方法完成后( onComplete ),并且一切正常,则调用原始的 onComplete1 块,并且工作正常.

但是,如果出现问题,则需要再次调用 problematicMethod (递归部分),并且在第一次发生这种情况时,我会立即收到EXC_BAD_ACCESS信号.

任何帮助将不胜感激.

解决方案

如何创建区块?请记住,您必须将其从堆栈移动到堆.

示例:

I am receiving EXC_BAD_ACCESS signal in my iOS application when doing a recursion that involves objective-c blocks. Here is the simplified code:

- (void)problematicMethod:(FriendInfo*)friendInfo onComplete:(void(^)(NSString*))onComplete1 {

[self doSomethingWithFriend:friendInfo onComplete:^(Response* response) {
    switch (response.status) {
        case IS_OK:
            onComplete1(message);
            break;

        case ISNT_OK:
            // Recursively calls the method until a different response is received 
            [self problematicMethod:friendInfo onComplete:onComplete1];
            break;          

        default:
            break;
    }
}];
}

So basically, the problematicMethod, in this simplified version, calls doSomethingWithFriend:onComplete:. When that method finishes (onComplete), and if everything was ok, the original onComplete1 block gets called, and this works fine.

But if something went wrong, problematicMethod needs to be called again (the recursion part), and when this happens for the first time, I immediately get EXC_BAD_ACCESS signal.

Any kind of help would be greatly appreciated.

解决方案

How are you creating your block? Remember that you have to move it from stack to heap.

Example:

 void(^onCompleteBlock)(NSString*) = [[^(NSString* param) {
  //...block code
}] copy] autorelease];

[self problematicMethod:friendInfo onCompleteBlock];

这篇关于在Objective-C中使用块递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆