Saturday, December 26, 2015

Is a delegate retained?

No, the delegate is never retained

Only for CAAnimation delegate retained
This is one of the rare exceptions to memory management rules.

Explanation:
It's a memory management thing.

Objective-C works with reference counts to keep the memory clean. This does mean that it can't detect cyclic relationships.

Example:

Object A owns object B. Object B is retained by object A.
Object B has a delegate that is object A. Object A is retained by object B.
Object C owns object A. Object A is retained by object C.
Object A now has a retainCount of 2, and object B has a retainCount of 1
Object C gets freed, and releases object A
Object A and B now have a retainCount of 1, because they own each other. The system will not free them, because the retainCount is still 1 (still owned by another object)
Memory leak!