Recursion with blocks in objective-c

隐身守侯 提交于 2019-12-22 10:09:05

问题


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.


回答1:


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];




回答2:


If response.status value is ISNT_OK you never finish calling recursively the function.



来源:https://stackoverflow.com/questions/11428531/recursion-with-blocks-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!