什么时候设置 Objective-C 属性双保留?

发布于 2024-08-21 13:06:36 字数 330 浏览 10 评论 0原文

给出以下代码

@interface MyClass
{
   SomeObject* o;
}

@property (nonatomic, retain) SomeObject* o;

@implementation MyClass
@synthesize o;

- (id)initWithSomeObject:(SomeObject*)s
{
   if (self = [super init])
   {
      o = [s retain]; // WHAT DOES THIS DO? Double retain??
   }
   return self
}

@end

Given the following code

@interface MyClass
{
   SomeObject* o;
}

@property (nonatomic, retain) SomeObject* o;

@implementation MyClass
@synthesize o;

- (id)initWithSomeObject:(SomeObject*)s
{
   if (self = [super init])
   {
      o = [s retain]; // WHAT DOES THIS DO? Double retain??
   }
   return self
}

@end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

逆夏时光 2024-08-28 13:06:36

它不是双重保留; s 只会保留一次。

原因是您没有在初始化程序中调用合成的 setter 方法。此行:

o = [s retain];

保留 s 并将 o 设置为等于 s;也就是说,os 指向同一个对象。合成的访问器永远不会被调用;您可以完全摆脱 @property@synthesize 行。

如果该行是:

self.o = [s retain];

或等效的

[self setO:[s retain]];

,则将调用合成访问器,这将再次保留该值。请注意,通常不建议在初始化程序中使用访问器,因此在编写 init 函数时,o = [s keep]; 是更常见的用法。

It is not a double retain; s will only be retained once.

The reason is that you're not invoking the synthesized setter method within your initializer. This line:

o = [s retain];

retains s and sets o to be equal to s; that is, o and s point to the same object. The synthesized accessor is never invoked; you could get rid of the @property and @synthesize lines completely.

If that line were:

self.o = [s retain];

or equivalently

[self setO:[s retain]];

then the synthesized accessor would be invoked, which would retain the value a second time. Note that it generally not recommended to use accessors within initializers, so o = [s retain]; is the more common usage when coding an init function.

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