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];
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.