iPhone Memory Management Rules-of-Thumb

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
Advertisements

2 Responses to “iPhone Memory Management Rules-of-Thumb”

  1. Jerry Says:

    (psst: pluralize the noun part of the phrase, e.g. “rules of thumb”)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: