Lets say we have three objects: a grandparent, parent and child. The grandparent retains the parent, the parent retains the child and the child retains the parent. The grandparent releases the parent.

What will happen in this case ?


Solution 1:

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.

Solution 2:

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