Three “Brain Triggers” for Remembering How to Manage Memory in Objective-C

by Clint on February 18, 2009

At some point every Cocoa and Cocoa Touch developer has to learn how to manage memory while programming with Objective-C.  Unfortunately, it can be a confusing topic if you’re inexperienced or new to the language and frameworks. After doing my own bit of ramp-up in this area a while ago, I distilled everything I learned into three “brain triggers,” or rules, that I can use to easily remember when and how to use -retain, -release, and -autorelease (the three main methods for managing memory in Objective-C). While somewhat similar to the “memory rules” presented in Apple’s 40-page Memory Management Programming Guide for Cocoa, I’ve found my own “brain triggers” to be easier to remember, and the accompanying notes easier to reference.  To that end, I decided to share the information here in case it’s helpful to anyone else.

A Quick Refresher on Memory Management Concepts


If it’s been awhile since you’ve had to think about memory management, a quick Comp Sci 101 refresher might be helpful. Recall that in an object-oriented programming environment, your program will allocate memory for each object that it creates. Similarly, your program is responsible for deallocating (aka “freeing”) that memory when the object is no longer being used; this allows the operating system to use that memory elsewhere. You have to be careful, though–freeing the memory prematurely will result in a dangling pointer, and conversely, failing to free an object that’s no longer being used causes a memory leak. The big question, then, is how do you know when it’s safe to deallocate an object?

One easy way to solve this problem is to use a technique called “reference counting.” Referencing counting is pretty simple: every object has an internal counter that keep track of how many pointers are, well, pointing to it. As more pointers reference the object, the reference count goes up. When a pointer stops referencing an object the reference count should go down. In other words: if an object’s reference count goes down to zero, you know it’s safe to deallocate it.

Most Objective-C classes inherits the aforementioned reference-counting mechanism from NSObject (a core class provided by the Foundation Framework). More specifically, nearly all objects have two methods used to increase/decrease the reference count: -retain and -release. Each time an object’s -retain method is called, its reference count is incremented. Conversely, calling an object’s -release method decrements the reference count. If you call -release on an object such that its reference count reaches zero, the -release method will free the memory being used by the object (literally calling the C “free” function). Finally, you can use the -retainCount method to access an object’s current reference count.

Note: While UIKit / Cocoa Touch applications running on the iPhone must use reference counting as described above, AppKit / Cocoa applications that run in OS X can take advantage of the garbage collection mechanism that was introduced with Objective-C 2.0 in 2006.

Three “Brain Triggers” For Remembering How to Use retain/release/autorelease

Once you understand the concept of reference counting and what NSObject’s -retain and -release methods do, you can start learning how and when to use them. At a high level, the rules of reference counting are as follows:

  1. If you allocate or copy an object, you are responsible for ensuring that it is released via -release or -autorelease.
  2. If someone else allocates an object that you reference for a long time, use -retain/-release to show ownership.
  3. If you add/remove objects to/from a collection, understand that the collection will automatically -retain/-release those objects.

Note that each rule is worded as a conditional statement and that the condition is in bold; these are the “brain triggers” that can be used to help make reference counting easier. The idea of a “brain trigger” is similar to a database trigger. As you’re writing code you should watch for these events to occur (e.g., “Hey, I just allocated an object in a convenience constructor–what am I supposed to do, again?“). This is your cue to take action (“Ah yes, I need to make sure I call -release or -autorelease!“).

Rule #1: If you allocate or copy an object, you are responsible for ensuring that it is released via -release or -autorelease.

When you allocate and initialize an object (or copy it) the object’s reference count is set to 1 for you by default. Because you caused the object’s reference count to be incremented, you are responsible for ensuring that it is also decremented at some point.

Scenario A: Allocating and releasing an object in the same code block

NSString *someStr = [[NSString alloc] initWithString:@"hello"]; // ref count 1
NSString *strCopy = [someStr copy]; // ref count 1

[someStr release]; // Decrement ref count to 0, causes object free itself
[strCopy release]; // Decrement ref count to 0, causes object free itself

Scenario B: Allocating in one block, releasing later inside the standard -dealloc method

Sometimes you can’t immediately release an object that you’ve created. If the object is stored as an instance variable, for example, you can release it later in your class’ -dealloc method.

@interface MyClass : NSObject
    NSString *_myStr;

@implementation MyClass

-(void) someMethod
    [_myStr release];
    _myStr = [[NSString alloc] initWithString:@"blah"];

    // Note: We release _myStr first in case this method has already
    // been called (i.e., an existing _myStr objects exists). Remember
    // that it's okay to call methods on null objects, so there's no
    // danger of a null pointer error.

-(void) dealloc
    [_myStr release];
    [super release];

    // Note: If -someMethod is never called, then _myStr will be null.
    // It's okay to send messages to null objects, however, so calling
    // release won't cause any problems.

Scenario C: Allocating objects, “giving them away,” and ensuring they’re released later via autorelease pools

What if your method creates and returns an object without keeping a reference to it? For example, this is a common scenario for “convenience constructor” methods which allocate, initialize, and return objects. Here’s an example:

+(SomeClass *) convenienceConstructor:(NSString *)name
    SomeClass *someObj = [[SomeClass alloc] init];
    return someObj;

In this situation, the convenience constructor method can’t release the object immediately; that would result in it returning a dangling pointer. Similarly, we’re not storing someObj as an instance variable so we can’t release it inside the object’s -dealloc method. So what do you do? One solution to this problem is to use autorelease pools. At a high level, it works like this:

  1. Ensure that a data structure (e.g., an array) exists outside the scope of the method that is allocating objects. This data structure essentially becomes the “pool of objects that need to be released later.”
  2. Code methods like the above convenience constructor such that they add each newly-created object to the “release later” pool before returning them.
  3. Ensure that all the objects in the “release later” pool are, well, released at some point.

Thankfully, Apple offers a few pre-made tools you can use to implement each step of this mechanism:

  • An NSAutoreleasePool class already exists which you can use as the “release later” pool described in Step 1.
  • Every class that extends NSObject inherits an -autorelease method which implements Step 2 (i.e., automatically adds the object to the “nearest” NSAutoreleasePool instance).
  • To release all the objects in the “release later” pool as described in Step 3, you can use the NSAutoreleasePool’s -drain (or -release) methods.
Note: Autorelease pools can be stacked (some might say “nested”); function A might create an NSAutoreleasePool instance and call function B, which creates another autorelease pool. When an object’s -autorelease method is called, it is added to the “nearest” autorelease pool. And when that pool is released, so are any objects it contains.

The code example below illustrates how you can use autorelease pools

// MainProgram.m
-(void) handleMainButtonClick
    // Create the auto-release pool for the scope of this method.
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // NSNumber is a Foundation Framework class. Note that we don't directly
    // allocate the NSNumber instance; the -numberWithInt method does
    // that for us and is therefore responsible for adding the object it allocates
    // to the nearest NSAutoreleasePool instance (i.e., the one created above).
    NSNumber *someNum = [NSNumber numberWithInt:123];

    // Again, we aren't directly allocating an instance of our custom
    // GreetingGenerator class; the -greetingWithName method should take
    // responsibility for adding it to the nearest NSAutoreleasePool
    GreetingGenerator *gen = [GreetingGenerator greetingWithName:@"Clint"];

    // Do stuff...

    [pool release];
    // Now the objects referenced by 'someNum' and 'gen' will be released when
    // the thread leaves this block and the autorelease pool is 'popped' off
    // the stack. Note that you could still call -retain on either of this objects
    // to prevent that from happening.
// GreetingGenerator.m

+(GreetingGenerator *) greetingWithName:(NSString *)name
    GreetingGenerator *generator = [[GreetingGenerator alloc] init];
    [generator setName:name];

    // We created "generator" and are responsible for ensuring that it is
    // released. We'll add the object to the nearest NSAutoreleasePool
    // instance so it can be released later. An instance of NSAutoreleasePool must
    // have been created before call -autorelease!
    [generator autorelease];

    return generator;

Here’s one final tip regarding autorelease pools. In some situations you may want to drain a pool to clean up memory but prevent specific objects from being deallocated. Simply call -retain on the objects you want to keep (i.e., increment their reference count so that it doesn’t reach 0 when the pool is drained). Here’s a contrived example:

-(void) someMethod
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString *string1 = [NSString stringWithString:@"blah"];
    NSString *string2 = [NSString stringWithString:string1];

    // Assume we have an instance variable called _string3
    _string3 = [NSString stringWithString:string2];
    [_string3 retain];
    [pool release];
    // string1 and string2 will now be deallocated when the method finishes, but
    // _string3 will remain since we incremented its ref count.

Rule #2: If someone else allocates an object for you, use -retain/-release to show ownership.

If your code receives a pointer to an object that it did not create, then you are not responsible for ensuring that it is released. Per Rule #1, the class that creates an object is responsible for ensuring that it is released. But how can you prevent the code this is responsible for this from releasing the object while you’re still using it? Call the object’s -retain method.

Sending the -retain message to an object will cause the its reference count to increment. Once you’re done using the object, however, you must call its -release method to decrement the object’s reference count. This will ensure that the reference count accurately reflects the number of “owners” it has; once all the owners call -release, the count should reach 0 and the object will free itself from memory.

Note: The example code below uses setter methods to illustrate Rule #2. It’s worth mentioning that, in the case of Cocoa development, setter methods often receive objects that were loaded from nib files (especially when building user interfaces). If you don’t really understand how nib files work, you might be wondering if Rule #2 still applies. The quick answer is: yes. Every object loaded from a nib is automatically added to an autorelease pool (i.e., its -autorelase method is called by the nib-loading mechanism). That said, the official Apple documentation regarding Nib files specifically states that if an object is loaded from a nib and passed to a setter method, that setter method should -retain the object. This ensures that it won’t be destroyed while you’re using it, even if the autorelease pool were released.

Scenario A: Hand-coded setter method

-(void) setImage: (UIImageView *)newImage
    // We didn't allocate the 'newImage' object so we'll assume that
    // whoever did was responsible and added it to an autorelease pool.
    // To ensure that it isn't destroyed while we're using it, we'll
    // manually call -retain.
    [newImage retain];

    // Release our old object (may be null, but that's okay)
    [_myImageView release]; 

    // Point our instance variable at the object being passed in
    _myImageView = newImage;

    /* Note: this pattern (i.e., retain the parameter, release the old ivar,
       then set the ivar to point at the parameter) is great because it also
       handles scenario in which newImage and _myImageView are both already
       pointing to the same object. Object's retain count will be inaccurately
       high when we call [newImage retain], but is immediately lowered to
       accurate count when we call [_myImageView release] on the next line.

-(void) dealloc
    [_myImageView release]; // We're done using this object
    [super release];

Scenario B: Auto-generated setter method

One of the big additions to Objective-C 2.0 is the @property and @synthesize directives, which can be used to automatically generate getter/setter methods for you. It’s important to remember that you still need to use -retain and -release as if you were manually coding a setter method. If you use the “retain” keyword in your @property declaration (as shown below), the generated setter method will essentially do the same thing as the hand-coded one shown above in Example A.

@interface Person : NSObject
    NSString *_name;
// This will be converted into a pair of getter/setter methods
@property (nonatomic, retain) NSString name;

@implementation Person

// Generate getter/setter methods
@synthesize name=_name;

-(void) dealloc
    // The setter method retained '_name', so now we must release
    [_name release];
    [super release];

Rule #3: If you add/remove objects to/from a collection, understand that the collection will automatically -retain/-release those objects.

It’s important to be aware of the fact that data structures such as NSMutableArray, NSDictionary, etc., will automatically -retain and -release objects when they are added/removed to and from the collection. Specifically, when you add an object to a collection its reference count is incremented. When you remove an object, the reference count is decremented. Finally, if you release the collection, the objects inside are also released.


NSMutableArray *numberArray = [NSMutableArray arrayWithCapacity:2];

NSNumber *num1 = [NSNumber numberWithInt:333];
NSNumber *num2 = [NSNumber numberWithInt:777];
// Both NSNumber instances currently have a reference count of 1

[numberArray addObject: num1];
[numberArray addObject: num2];
// Both NSNumber instances currently have a reference count of 2

[num1 release];
[num2 release];
// Both NSNumber instances currently have a reference count of 1

// Remove last number from the array ("777")
NSNumber *lastNumber = [numberArray objectAtIndex:[numberArray count]-1];
[lastNumber retain]; // "777" instance now has ref count of 2
[numberArray removeLastObject]; // "777" instance now has ref count of 1
[lastNumber release]; // Decrements "777" ref count to 0, object frees itself

// Release the array, triggering all objects inside to be released.
// Specifically, the "333" number instance will have its ref count
// decremented from 1 to 0, thus causing it to release itself.
[numberArray release];


If all of this leaves you thinking, “Whew, that’s a lot to remember!” don’t worry–the point here is that you don’t need to memorize everything at once. Just memorize the “triggers” (i.e., the three “if” statements):

  1. If you allocate or copy an object, you are responsible for ensuring that it is released via -release or -autorelease.
  2. If someone else allocates an object that you reference for a long time, use -retain/-release to show ownership.
  3. If you add/remove objects to/from a collection, understand that the collection will automatically -retain/-release those objects.

These will at least remind you to look up information on what you need to do.

Clint Harris is an independent software consultant living in Brooklyn, New York. He can be contacted directly at ten.sirrahtnilc@tnilc.
  • Eric Christopherson

    Excellent writeup. One nitpick though, and forgive me if this has been brought up before, or if you have a darn good reason for it: -release and -retain don’t have any colons in them. I think the convention is to only put colons at the end when the actual selector ends in a colon.

  • Clint

    @Eric Christopherson: Thanks for the feedback! Good point about selector convention–I’ve updated the post.

  • John Varghese

    Excellent write up. Spot on.