Alex Gosselin
Alex Gosselin

Reputation: 2930

Do IBOutlet member vars retain automatically?

Weird discovery, when I used a drag and drop to make a new IBOutlet, as shown below, not with a @property at all:

@interface SkinChoosingView : UIViewController {
    IBOutlet UIActivityIndicatorView * activityIndicator;
}

Xcode inserted a -release and set the outlet to nil in viewDidUnload. I looked in viewDidLoad though, and no -retain was there! This went against everything I know about memory management.

I figure apple must know a thing or two about this stuff though, so is there something behind the scenes happening here? I have never had leaks from these types of IBOutlets, and I've never released them.

Upvotes: 1

Views: 532

Answers (2)

tc.
tc.

Reputation: 33592

The answer is that it uses "Key-Value Coading", which means it calls -setValue:forKey:, which has a "Default Search Pattern". For ivars, it does something like [ivar autorelease]; ivar = [newvalue retain];.

The "current best practice" is to stick IBOutlet on properties instead of ivars (see here). This makes it obvious what memory management pattern is being used and is more resilient to typos (e.g. if you misspell the ivar).

Upvotes: 1

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

Yes, it automatically retains the outlet for you when loading the NIB file unless you explicitly declare the property associated with the outlet as an assigned property.

And since it retains the outlet for you, you must release in viewDidUnload as the outlets will be reloaded by the time next viewDidLoad is called.

Upvotes: 3

Related Questions