How to Avoid Strong Reference Cycles
- Avoid strong delegates
- Avoid strong IBOutlet
- Avoid strong reference variable inside the Blocks
Although strong references work well for one-way relationships between objects, you need to be careful when working with groups of interconnected objects. If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from outside the group.
One obvious example of a potential reference cycle exists between a table view object (UITableView for iOS and NSTableView for OS X) and its delegate. In order for a generic table view class to be useful in multiple situations, it delegates some decisions to external objects. This means it relies on another object to decide what content it displays, or what to do if the user interacts with a specific entry in the table view.
Use Weak References to Avoid Retain Cycles
Retaining an object creates a strong reference to that object. An object cannot be deallocated until all of its strong references are released. A problem, known as a retain cycle, can therefore arise if two objects may have cyclical referencesthat is, they have a strong reference to each other (either directly, or through a chain of other objects each with a strong reference to the next leading back to the first).
The object relationships shown in https://developer.apple.com/Library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Art/retaincycles_2x.png
illustrate a potential retain cycle. The Document object has a Page object for each page in the document. Each Page object has a property that keeps track of which document it is in. If the Document object has a strong reference to the Page object and the Page object has a strong reference to the Document object, neither object can ever be deallocated. The Documents reference count cannot become zero until the Page object is released, and the Page object wont be released until the Document object is deallocated.
The solution to the problem of retain cycles is to use weak references. A weak reference is a non-owning relationship where the source object does not retain the object to which it has a reference.
To keep the object graph intact, however, there must be strong references somewhere (if there were only weak references, then the pages and paragraphs might not have any owners and so would be deallocated). Cocoa establishes a convention, therefore, that a parent object should maintain strong references to its children, and that the children should have weak references to their parents.