@property(retain) 的作用是什么?
@propert(retain) 是做什么的?通过我的测试,它实际上并没有保留我的对象:
id obj = getObjectSomehow();
NSLog(@"%d", [obj retainCount]);
propertyWithRetain = obj;
NSLog(@"%d", [obj retainCount]);
// output:
// 1
// 1
如何创建一个真正保留该对象的属性?
What does @propert(retain) do? it doesn't actually retain my object by my tests:
id obj = getObjectSomehow();
NSLog(@"%d", [obj retainCount]);
propertyWithRetain = obj;
NSLog(@"%d", [obj retainCount]);
// output:
// 1
// 1
How can I make a property that will really retain the object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有在那里使用您的财产,这就是它不保留的原因!
试试这个:
使用
self.
将使用该属性。仅使用变量名称不会。特别是对@bbum进行编辑(他在评论中提出了一个非常公平的观点)
不要依赖于使用retainCount - 你不知道还有什么保留了你的对象,并且你不知道其中一些保留是否实际上是计划的自动释放所以这通常是一个误导性的数字:)
You're not using your property there, that's why it's not retaining!
Try this :
Using
self.
will use the property. Just using the variable name won't.EDIT especially for @bbum (who raises a very fair point in the comments)
Don't rely on using retainCount - you don't know what else has retained your object and you don't know if some of those retains are actually scheduled autoreleases so it's usually a misleading number :)
这只是设置 ivar 直接支持该属性。当@property被合成时,如果没有声明实例变量,则会自动生成一个。上面是直接使用那个ivar。
这实际上会通过 @synthesized setter 并增加保留计数。
这也是为什么我们许多人使用 @synthesize propertyWithRetain = propertyWithRetain_; 来导致 iVar 以不同的方式命名。
请注意,即使在这种情况下,调用
retainCount
也可能会产生严重的误导。尝试使用[NSNumber numberWithInt: 2];
或常量字符串。真的,不要调用retainCount
。从来没有。That just sets the ivar backing the property directly. When an @property is synthesized, if there is no instance variable declared, then one is generated automatically. The above is using that ivar directly.
That would actually go through the
@synthesize
d setter and bump the retain count.Which is also why many of us use
@synthesize propertyWithRetain = propertyWithRetain_;
to cause the iVar to be named differently.Note that, even in this, calling
retainCount
can be horribly misleading. Try it with[NSNumber numberWithInt: 2];
or a constant string. Really, don't callretainCount
. Not ever.