开发者

When does setting an Objective-C property double retain?

Given the following code

@interface MyClass
{
   SomeObject* o;
}

@property (nonatomic, retain) SomeObject* o;

@implementation MyClass
@synthesize o;

- (id)initWithSomeObjec开发者_开发百科t:(SomeObject*)s
{
   if (self = [super init])
   {
      o = [s retain]; // WHAT DOES THIS DO? Double retain??
   }
   return self
}

@end


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜