iOS dev tip #2: Release your IBOutlets
This tip is somewhat related to the previous one – in fact, most of the problems I’ve seen in iOS code stem from misunderstanding the memory management model, so I’d like to cover at least some of that area in the first few tips. On to the second one.
When declaring your member variables as IBOutlet, always remember to release them under iOS. This is a very common mistake; if you just load the view from the Nib and don’t specifically retain the outlets, it doesn’t look like there’s a reason to manually release them.
However, the iOS implementation retains the outlets even if you don’t do it manually. Here’s an excerpt from the Resource programming guide:
Objects in the nib file are created with a retain count of 1 and then autoreleased. As it rebuilds the object hierarchy, however, UIKit reestablishes connections between the objects using the setValue:forKey: method, which uses the available setter method or retains the object by default if no setter method is available. If you define outlets for nib-file objects, you should always define a setter method (or declared property) for accessing that outlet. Setter methods for outlets should retain their values, and setter methods for outlets containing top-level objects must retain their values to prevent them from being deallocated. If you do not store the top-level objects in outlets, you must retain either the array returned by the loadNibNamed:owner:options: method or the objects inside the array to prevent those objects from being released prematurely.
In short, if you declare a setter method for your outlet, that method will be called. Otherwise, the outlet will be retained before setting it directly on the object using setValue:forKey:.
Note that this is different behavior than on MacOS X, where the object won’t be automatically retained if there’s no retain-ing property.
Next time I’ll be explaining the UIViewController view and memory management, and important but also often misunderstood concept in iOS development. Stay tuned :)
If you have some tips to add, I’d love to hear from you!

