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
self.myProperty = [[MyClass alloc] init];
Use ARC to generate your releases and retains at compile time.
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 is correct.
Option 2 is absolutely wrong. You never call -release
on the results of a property accessor.
Option 3 is avoiding properties entirely. This is actually correct in your -init
method, but in other methods it's better to use the property setter unless you have a good reason to avoid it.
Option 4 is correct as well, though it's more verbose than option 1. Your call.
Edit: I misread your option 4 originally.
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.