November 23, 2010
Posted by on
This rule is taken on the book titled Creating iPhone Application with Cocoa Touch and like to share this wisdom with others:
Longtime Cocoa programmers will cite the following rules, originally written by Don Yacktman, whenever you ask a question about how tomanage memory:
• If you allocated, copied, or retained an object, then you’re responsible for releasing the object with either –release or –autorelease when you no longer need the object. If you did not allocate, copy,or retain an object, then you should not release it.
• When you receive an object (as the result of a method call), it will normally remain valid until the end of your method, and the object can be safely returned as a result of your method. If you need theobject to live longer than this—for example, if you plan to store itin an instance variable—then you must either –retain or –copy theobject.
• Use –autorelease rather than –release when you want to return an object but also wish to relinquish ownership of the same. Use –release wherever you can, for performance reasons.
• Use –retain and –release (or –autorelease) when you want toprevent an object from being destroyed as a side effect of the operations you’re performing.