什么时候设置 Objective-C 属性双保留?
给出以下代码
@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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不是双重保留;
s
只会保留一次。原因是您没有在初始化程序中调用合成的 setter 方法。此行:
保留
s
并将o
设置为等于s
;也就是说,o
和s
指向同一个对象。合成的访问器永远不会被调用;您可以完全摆脱@property
和@synthesize
行。如果该行是:
或等效的
,则将调用合成访问器,这将再次保留该值。请注意,通常不建议在初始化程序中使用访问器,因此在编写
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:
retains
s
and setso
to be equal tos
; that is,o
ands
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:
or equivalently
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 aninit
function.