How do I avoid capturing self in blocks when implementing an API?
Short answerInstead of accessing
The If you are using ARC, the semantics of Long answerLet's say you had code like this:
The problem here is that self is retaining a reference to the block; meanwhile the block must retain a reference to self in order to fetch its delegate property and send the delegate a method. If everything else in your app releases its reference to this object, its retain count won't be zero (because the block is pointing to it) and the block isn't doing anything wrong (because the object is pointing to it) and so the pair of objects will leak into the heap, occupying memory but forever unreachable without a debugger. Tragic, really. That case could be easily fixed by doing this instead:
In this code, self is retaining the block, the block is retaining the delegate, and there are no cycles (visible from here; the delegate may retain our object but that's out of our hands right now). This code won't risk a leak in the same way, because the value of the delegate property is captured when the block is created, instead of looked up when it executes. A side effect is that, if you change the delegate after this block is created, the block will still send update messages to the old delegate. Whether that is likely to happen or not depends on your application. Even if you were cool with that behavior, you still can't use that trick in your case:
Here you are passing
This solution avoids the retain cycle and always calls the current delegate. If you can't change the block, you could deal with it. The reason a retain cycle is a warning, not an error, is that they don't necessarily spell doom for your application. If You could also look into using a similar trick above, declaring a reference weak or unretained and using that in the block. For example:
All three of the above will give you a reference without retaining the result, though they all behave a little bit differently: What's best will depend on what code you are able to change and what you cannot. But hopefully this has given you some ideas on how to proceed. |
|||
add / show 5 more comments |
There’s also the option to suppress the warning when you are positive that the cycle will get broken in the future:
That way you don’t have to monkey around with |
|||||||||||||||
|
I believe the solution without ARC also works with ARC, using the EDIT: Per the Transitioning to ARC Release Notes, an object declared with
|
|||||||||||||||||||||
|
For a common solution, I have these define in the precompile header. Avoids capturing and still enables compiler help by avoiding to use
Then in code you can do:
|
dp
will be released (for example if it was a view controller and it was poped), then line[dp.delegate ...
will cause EXC_BADACCESS? – peetonn Jan 30 '13 at 1:50