This is a great document from Apple on Objective-C / iPhone memory management and the practical cookbook tips on retain/release. I suspect that you have to be logged into Apple Developer Network website to read the document. I’ve read it a while ago and re-read it over the weekend. You should read it from beginning to end a few times 🙂
Here are a few quick rules-of-thumb I use.
- If the message that gave you an object does not have “alloc”, “new”, “copy”, “retain”, you don’t have to release the object. In other words, calls to [NSDictionary dictionaryWithContentsOfURL: …] and [NSString stringWithFormat: …] are cool. These are convenience functions.
- Objects in a collection (i.e. NSDictionary, NSArray, etc.) are managed by the collection. The implementation of the collection takes care of the retain/release. When you release the collection itself, the implementation will release the objects in the collection.
- Autorelease Pools should be used sparingly – You wouldn’t need to create Autorelease Pools yourself unless you are running things in a thread you spawned. Refer to the document. Autorelease Pool is NOT garbage collection, it is an extension to the retain/release reference count memory management system.
- UI Objects loaded from NIB files use Assessor methods. If you declare @property with (nonatomic, retain) for the IBOutlet instance variables and use @synthesize, you do not need to do anything with with retain yourself, but you do have to release them in your dealloc() method. If you create your own UIView objects from a ViewController, you are responsible for cleaning up after yourself.
- Use Assessor Methods in your code. My rules-of-thumb are:
- Always use @property / @synthesize
- Set values to instance variables with self.variable = …
- Get values to instance variables with just variable. Some may question this specific rule of thumb on the basis of consistency with the rule above. I can be sway the other way, but since we use instance variables a lot more than setting instance variables, I use this rule to make my code more readable. See following rule.
- Be consistent. Alternatively, although a bit more verbose, set values with [self setVariable: …] and get values with self.variable.
January 7, 2010 at 9:17 am |
(psst: pluralize the noun part of the phrase, e.g. “rules of thumb”)
January 7, 2010 at 9:36 am |
Thanks! Will fix.