Cocoa memory management

Here is extraction of simple memory management rules for Cocoa Framework

The important things to remember about memory management in Cocoa distill down to these rules of thumb:

  • Objects created by alloc or copy have a retain count of 1.
  • Assume that objects obtained by any other method have a retain count of 1 and reside in the autorelease pool. If you want to keep it beyond the current scope of execution, then you must retain it.
  • When you add an object to a collection, it is retained. When you remove an object from a collection, it is released. Releasing a collection object (such as an NSArray) releases all objects stored in it as well.
  • Make sure that there are as many release or autorelease messages sent to objects as there are alloc, copy, mutableCopy, or retain messages sent. In other words, make sure that the code you write is balanced.
  • Retain, then release objects in setter methods.
  • NSString objects created using the @" . . . " construct are effectively constants in the program. Sending retain or release messages to them has no effect. This explains why we haven’t been releasing the strings created with the @" . . . " construct.



Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s