Memory Management and NIBs on the iPhone

There's clearly some confusion out there among iPhone developers about whether or not you need to release your IBOutlets. It's actually pretty simple.

When UIKit loads a NIB file, it sets up all your IBOutlets for you. That is, after all, then entire point of an IBOutlet! UIKit does this using setValue:forKey: which is part of the NSKeyValueCoding Protocol. The important things to know about it are:

  • If you have a setter method (which you will if you have defined it as an @property), UIKit will call that
  • If you have not defined a setter, then UIKit will directly set the value of the instance variable and then, for anything other than an NSNumber or NSValue date type, UIKit will retain the value after autoreleasing the instance variable's old value.

The consequence of this is that unless you define your IBOutlets as

@property (..., assign)

then you need to worry about cleaning them up at dealloc time. A good way to do this is to ensure that you always define an IBOutlet as an @property, and then to simply to set their values to nil in your dealloc implementation, like this:

-(void)dealloc {
    self.outlet1 = nil;
    self.outlet2 = nil;
    [super dealloc];

Setting them to nil will work regardless of how you set up the @property - i.e. whether it is a 'retain'-type or an 'assign'-type property.

You also need to worry about IBOutlets in UIViewController when handling didReceiveMemoryWarning, but that's a story for another post.