Retain cycles. We’ve all likely been bitten by it at least once. Especially with the increasing role blocks/closures play in modern day iOS development. As you probably already know, referencing any object from inside a block captures a strong reference to it, and if that object copies/retains the block, it results in a retain cycle, that could cause a memory leak unless the block is manually nil
’ed out.
There’s of course a well-known way to avoid this problem. Use a weak reference with the __weak
qualifier, but while looking at Facebook’s Pop open source project, I came across an interesting alternate solution.
/**
@param target The object being animated.
Reference the passed in target to help avoid retain loops.
*/
typedef BOOL (^POPCustomAnimationBlock)(id target, POPCustomAnimation *animation);
The parameters in the block are, in a way, redundant, because you can always get an implicit reference to these variables (through block’s scope variable capturing), but it’s very useful because now you can use these parameters rather than declaring a weak reference outside a block and using that.
This way you avoid retain cycles without having to do the whole strong → weak dance.
So the next time you’re designing an API that has a block or closure, keep this tip in mind.