简体   繁体   中英

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)initWithSomeObject:(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM