2010-02-12 32 views
4

鉴于以下代码什么时候设置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 

回答

12

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

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

o = [s retain]; 

保留s并设置o为等于s;即os指向同一个对象。从不调用合成的存取器;你完全可以摆脱@property@synthesize行。

如果该行是:

self.o = [s retain]; 

或等效

[self setO:[s retain]]; 

然后将合成的访问将被调用,这将保持值的第二时间。请注意,通常不建议在初始化程序中使用访问器,因此编码init函数时o = [s retain];是更常见的用法。

相关问题