Recursion with blocks in objective-c

I get an EXC_BAD_ACCESS signal in an iOS application when doing a recursion with 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, problematicMethod, in this simplified version, calls doSomethingWithFriend: onComplete :. When this method finishes (onComplete), and if everything is ok, the original onComplete1 block is called, and this works fine.

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

Any help is appreciated.

+3
source share
2 answers

How do you create your block? Remember that you need to move it from the stack to the heap.

Example:

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

[self problematicMethod: friendInfo onCompleteBlock];

+2
source

If the response.status value is ISNT_OK, you never end the function call recursively.

0
source

Source: https://habr.com/ru/post/1447202/


All Articles