Recursion with blocks in objective-c

2019-05-14 07:20发布

问题:

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.