Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 731
Greg Avatar asked Oct 17 '25 20:10

Greg


1 Answers

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'.

like image 180
Stepan Hruda Avatar answered Oct 19 '25 13:10

Stepan Hruda