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