Sunday, April 2, 2017

Avoid retain cycles without doing Strong to Weak

April 02, 2017 Posted by CHANDAN MAKHIJA No comments
You all will be familiar with blocks. It plays a very important role in iOS development. When you are using blocks you might have come across with Retain Cycles. 

Retain Cycle is the condition When 2 objects keep a reference to each other and are retained, it creates a retain cycle since both objects try to retain each other, making it impossible to release.
Here the "Grandparent" retains the "parent" and "parent" retains the "child" where as "child" retains the "parent". Here a retain cycle is established between parent and child. After releasing the Grandparent both the parent and child become orphaned but the retain count of parent will not be zero as it is being retained by the child and hence causes a memory management issue.
 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.
So to avoid these Retail Cycles we use a weak reference with the __weak qualifier. But when i was searching some other way of doing it, i found one alternate solution for it. While going through Facebook’s Pop open source project, I came across this method.

/**@param target The object being animated.Reference the passed in target to help avoid retain loops.*/typedef BOOL (^POPCustomAnimationBlock)(id target, POPCustomAnimation *animation);
Look at the parameters of the block 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.

0 comments:

Post a Comment