简体   繁体   English

IBOutlet成员变量会自动保留吗?

[英]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: 奇怪的发现,当我使用拖放来创建一个新的IBOutlet时,如下所示,根本没有使用@property:

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

Xcode inserted a -release and set the outlet to nil in viewDidUnload . Xcode插入-release并在viewDidUnload中将插座设置为nil。 I looked in viewDidLoad though, and no -retain was there! 我在viewDidLoad中看起来虽然没有-retain在那里! 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. 我从来没有从这些类型的IBOutlets泄漏,我从来没有发布它们。

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. 是的,它会在加载NIB文件时自动保留插座,除非您明确声明与插座关联的属性为assign属性。

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. 并且由于它为您保留了插座,因此必须在viewDidUnload释放,因为在调用下一个viewDidLoad时将重新加载插座。

The answer is that it uses "Key-Value Coading", which means it calls -setValue:forKey: , which has a "Default Search Pattern" . 答案是它使用“Key-Value Coading”,这意味着它调用-setValue:forKey: ,它具有“默认搜索模式” For ivars, it does something like [ivar autorelease]; ivar = [newvalue retain]; 对于ivars,它有点像[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 ). “当前的最佳实践”是将IBOutlet粘贴在属性而不是ivars上(参见此处 )。 This makes it obvious what memory management pattern is being used and is more resilient to typos (eg if you misspell the ivar). 这使得显而易见的是正在使用的内存管理模式以及对拼写错误更具弹性(例如,如果拼错了ivar)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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