Greg
Greg

Reputation: 9168

Best practices for initialising Objective-C properties

I understand that this may not necessarily apply to just @properties, but they would be the most common use case. If there is, for example:

@property (strong) NSObject *object;

...

@synthesize object = _object;

It is possible to initialise it in the init method of the class it is declared in like so:

- (id)init {
    self = [super init];
    if (self) {
        _object = [[NSObject alloc] init];
    }
}

or override the getter and initialise it upon first use:

- (NSObject *)object {
    if (!_object) {
        _object = [[NSObject alloc] init];
    }
    return _object;
}

Which of these is it better to use? Does this depend on the use scenario (e.g. does the object the property is declared in have multiple initialisers, or the type of the property, how it's used, etc.)?

The real advantage I see in overriding the getter is that the property will only be allocated when it is needed, but a disadvantage would be that the first access would be slower.

On a side note, when accessing properties in the init method, is it better to access them as self.object or _object?

Upvotes: 4

Views: 7300

Answers (2)

Stepan Hruda
Stepan Hruda

Reputation: 596

Contrary to the accepted answer, Advanced Memory Management Programming Guide says you should use instance variables in the initializers and in the dealloc method. See 'Don’t Use Accessor Methods in Initializer Methods and dealloc'.

Upvotes: 7

AndersK
AndersK

Reputation: 36082

personally i find initializing in the init method is better, the life expectancy of the object is then more clear and also consider if the init fails for the object, isn't it better to get that at the init than when you do a get?

i also prefer to use self.object for properties because it uses the getter and setter of the object and the "self." makes it clear and to avoid situations where a retain is needed or not. sure in some cases like in your example it may cause a couple more lines of code but i rely on the compiler to optimize the code.

e.g.

yourobjclass* tmp = [[yourobjclass alloc] init];
self.object = tmp;
[tmp release];

Upvotes: 2

Related Questions