Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 564
DevDevDev Avatar asked Dec 18 '22 03:12

DevDevDev


1 Answers

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.

like image 175
BJ Homer Avatar answered Dec 28 '22 19:12

BJ Homer