Understanding retain cycle in depth

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.

There are two possible solutions:

1) Use weak pointer to parent , i.e a child should be using weak reference to parent, which is not retained.

2) Use "close" methods to break retain cycles.

http://www.cocoawithlove.com/2009/07/rules-to-avoid-retain-cycles.html


Unless there is some other reference to the parent or child, they both become orphaned. But the retain cycle between the parent and child prevent either from being released and they become wasted memory.

A child should never retain a parent. If anything, use a weak reference in the child to maintain a reference to the parent.


In a simple case, consider two objects A and B where A creates and retains B. When A is created, it creates B. When whoever created A finally releases it, A's retain count drops to zero and it gets deallocated. If A's dealloc method calls release on B, B's retain count also drops to zero and it also gets deallocated. [This assumes that nobody else has retained A or B, because I'm keeping things simple.]

But what happens if B needs a reference back to A, and it retains A? Whoever created A might release it. But since B has also retained A, A's retain count won't go to zero. Likewise, since A retains B, B's retain count also won't go to zero. Neither will be deallocated. Even if B calls A's release method in its own dealloc it doesn't matter, because that method is never going to be called.

At this point you have a memory leak, because you don't have any reference to A or B even though they both still exist. If A or B is doing anything processor intensive then you might also be leaking CPU time to unwanted objects.

In your case A is parent and B is child and whosoever created A is grandparent.


A retain cycle is a loop that happens when Object A retains Object B, and Object B retains Object A. In that situation, if either object is released:

  • Object A won't be deallocated because Object B holds a reference to it (retain count > 0).
  • Object B won't ever be deallocated as long as Object A has a reference to it (retain count > 0).
  • But Object A will never be deallocated because Object B holds a reference to it (retain count > 0).
  • till infinity

Thus, those two objects will just hang around in memory for the life of the program even though they should, if everything were working properly, be deallocated.