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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With