@property(retain) 的作用是什么?

发布于 2024-11-15 20:23:48 字数 246 浏览 1 评论 0原文

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我恋#小黄人 2024-11-22 20:23:48

您没有在那里使用您的财产,这就是它不保留的原因!

试试这个:

id obj = getObjectSomehow();
NSLog(@"%d", [obj retainCount]);
self.propertyWithRetain = obj; // Note the self. :)
NSLog(@"%d", [obj retainCount]);

使用 self. 将使用该属性。仅使用变量名称不会。


特别是对@bbum进行编辑(他在评论中提出了一个非常公平的观点)

不要依赖于使用retainCount - 你不知道还有什么保留了你的对象,并且你不知道其中一些保留是否实际上是计划的自动释放所以这通常是一个误导性的数字:)

You're not using your property there, that's why it's not retaining!

Try this :

id obj = getObjectSomehow();
NSLog(@"%d", [obj retainCount]);
self.propertyWithRetain = obj; // Note the self. :)
NSLog(@"%d", [obj retainCount]);

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 :)

枫以 2024-11-22 20:23:48
propertyWithRetain = obj;

这只是设置 ivar 直接支持该属性。当@property被合成时,如果没有声明实例变量,则会自动生成一个。上面是直接使用那个ivar。

self.propertyWithRetain = obj;

这实际上会通过 @synthesized setter 并增加保留计数。

这也是为什么我们许多人使用 @synthesize propertyWithRetain = propertyWithRetain_; 来导致 iVar 以不同的方式命名。

请注意,即使在这种情况下,调用 retainCount 也可能会产生严重的误导。尝试使用 [NSNumber numberWithInt: 2]; 或常量字符串。真的,不要调用 retainCount。从来没有。

propertyWithRetain = obj;

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.

self.propertyWithRetain = obj;

That would actually go through the @synthesized 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 call retainCount. Not ever.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文