简体   繁体   中英

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.

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 assign ed 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.

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]; [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 (eg if you misspell the ivar).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM