Which is the best way to handle creating an object to live in a retained property? I've included several examples.
Assume the property is:
@property (nonatomic, retain) myProperty;
@synthesize myProperty = _myProperty;
Option 1:
self.myProperty = [[[MyClass alloc] init] autorelease];
Option 2:
self.myProperty = [[MyClass alloc] init];
[self.myProperty release];
Option 3:
_myProperty = [[MyClass alloc] init];
Option 4:
MyClass *property = [[MyClass alloc] init];
self.myProperty = property;
[property release];
If in initialization of the object which holds the variable:
1) no. it's bad form to call through accessors in partially constructed states (e.g. init
, dealloc
)
2) no. it's bad form to call through accessors in partially constructed states (e.g. init
, dealloc
)
3) correct.
Exception: If your ivars are not private and you are in the implementation of a subclass of the type which declared the property, then you must also check to see if the parent class initialized the property. it's best to make the properties private or otherwise not directly accessible to subclasses.
4) no. it's bad form to call through accessors in partially constructed states (e.g. init
, dealloc
)
When you're working with a fully constructed instance:
1) this is fine when readbaility is more important than keeping your heap sizes low.
2) bad. the object returned from the getter is not necessarily the object you assigned.
3) bad. may introduce a leak if _myProperty
is not nil
.
4) best
Option 1: Acceptable... but you're wasting resources with autorelease. The reference gets added to a list of items that need to get released at the end of the run loop... your variable stays around until then even if it doesn't need to.. etc, etc. I believe this option is used frequently... but I also believe it's lazy and wasteful.
Option 2: Confusing. Nothing wrong with it, per-se, but I'd say it's bad form.
Option 3: Acceptable, but not ideal. What if there is a custom setter? Etc. I'd personally only use this form within a custom setter itself, or, possibly in a class initializer. Otherwise, you're missing out on some of the benefits of properties.
Option 4: Best.
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