Objective C Blocks as Async-callbacks & BAD ACCESS

Viewed 3454

I've got a serious doubt. Suppose the following scenario:

  1. You have a UIViewController onscreen.
  2. The app initiates, say, a backend call using a block as a callback
  3. You use a 'self' surrogate, to prevent retain cycles.
  4. The user hits 'Back', and the UIViewController gets dealloc'ed.
  5. Sooner or later, the callback block gets executed >> BAD ACCESS

Before iOS 4, we dealt with this kind of situation by setting to nil the delegate property of... i don't know, whatever class you were using.

But nowadays... how do you cancel a block??. What if the block was sent to a static method, and you have no way of wiping out that callback reference??.

In that case, should we avoid using the 'self' surrogate?

BTW, by 'self' surrogate, i mean to say:

__block typeof(self) bself = self;

Thanks!!

2 Answers
Related