Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion with blocks in objective-c

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.

like image 324
Misa Avatar asked Nov 22 '25 06:11

Misa


1 Answers

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

like image 118
Sulthan Avatar answered Nov 24 '25 22:11

Sulthan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!