通过与自动生成的代码 Xcode 4 进行比较来理解 @property 属性
我对属性的使用有一些疑问。通过阅读ARC过渡文档,应该使用strong和weak来代替retain和assign。
然而,至少在两种情况下,Xcode 自动生成的代码正在执行其他操作。我想知道这是否只是 Xcode 的“仍未更新”工具,或者我是否遗漏了某些内容。
第一种情况是 Core Data 托管对象自动生成。
创建相关类后,.h 文件中会出现以下内容:
@property(nonatomic,retain) NSString *myProperty;
在这种情况下编译器在做什么?将 retain
替换为 strong
?
但最奇怪的情况(由于我缺乏知识)是使用 IBOutlet
,将 Interface Builder 出口与 .h 文件连接时自动生成的代码是这样的:
@property (unsafe_unretained, nonatomic) IBOutlet UILabel *myOutlet;
这似乎与推荐的“弱”属性不同。我的意思是由各种论坛上的用户推荐。
而这个是在viewDidUnload:
中添加的,
- (void)viewDidUnload {
[self setMyOutlet:nil];
}
为什么我们需要这个语句呢?即使通过运行探查器工具,也没有发现内存泄漏或其他内存问题的痕迹?我的意思是,如果不设置为 nil ,一切都会正常工作。
I have a few doubts regarding the use of attributes. By reading the ARC transition document, strong and weak should be used in place of retain and assign.
However there are at least two cases where Xcode auto generated code is doing something else. I would like to know if this is just a 'still not updated' tool from Xcode, or if I am missing something.
The first case is with Core Data managed object auto generation.
After having created the relevant classes, this is what appears in a .h file:
@property(nonatomic,retain) NSString *myProperty;
what is the compiler doing in this case? Replace retain
with strong
?
But the strangest case (for my lack of knowledge) is with IBOutlet
, the auto generated code when connecting Interface Builder outlet with .h file is this:
@property (unsafe_unretained, nonatomic) IBOutlet UILabel *myOutlet;
and again this seems different from the recommended 'weak' attributes. I mean recommended by users on various forum.
And this is added in viewDidUnload:
- (void)viewDidUnload {
[self setMyOutlet:nil];
}
why do we need this statement? Even though by running the profiler instruments there's no trace of memory leak or other memory issue? I mean, without setting to nil
everything works fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
unsafe_unretained
将存储一个unsafe 指针,即当您的标签消失时该指针仍然存在,但它会指向一些垃圾。这就是-viewDidUnload
代码在此时将该指针重置为nil
的原因。当指针指向的对象消失时,使用弱属性会自动将指针值变为 nil。这就是推荐它的原因。retain
和strong
基本上是同一件事。该对象将被保留,即不会消失,直到该属性被设置为另一个值(例如nil
),此时该对象被释放。unsafe_unretained
will store an unsafe pointer, i.e. the pointer will still be there when your label goes away, but it'll point to some garbage. That's why the-viewDidUnload
code resets that pointer tonil
at that point. Usingweak
properties will automagically turn the pointer value intonil
when the object it points to goes away. That's why it's recommended.retain
andstrong
are basically the same thing. The object is retained, i.e. will not go away until the property is set to another value (e.g.nil
) at which point the object is released.