When is the save setting for the Objective-C property saved?

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 
+4
source share
1 answer

This is not a double retention; s will be saved only once.

The reason is because you are not using the synthesized setter method in your initializer. This line:

 o = [s retain]; 

saves s and sets o to s ; that is, o and s point to the same object. A synthesized accessory is never called; you can completely get rid of @property and @synthesize .

If this line was:

 self.o = [s retain]; 

or equivalent

 [self setO:[s retain]]; 

then a synthesized accessor will be called, which will save the value a second time. Please note that it is usually not recommended to use accessors in initializers, therefore o = [s retain]; is more common when encoding the init function.

+12
source

Source: https://habr.com/ru/post/1301165/


All Articles