views:

137

answers:

2
SomeObject *temp = [[SomeObject alloc] init]
self.theObject = temp;
[temp release];

Why is it always done that way? Why not

self.theObject = [[SomeObject alloc] init];
+1  A: 

The second version leaks the SomeObject instance, since self.theObject will call a setter that, if properly written, retains the object.

You could just do

theObject = [[SomeObject alloc] init];

and some people certainly do. Others prefer to always use accessors though, either for consistence or to avoid bugs if the accessors have side effects (for exmaple, you would be bypassing KVO notification, which could be a problem if it's not part of an init method).

smorgan
+11  A: 

If the theObject property is a retaining property, the first way is correct, because it doesn't leak memory. It's also more efficient than the correct way to write the second version, which is this:

self.theObject = [[[SomeObject alloc] init] autorelease];

Whenever you create an object with alloc you're in charge of releasing it somehow, whether by release or autorelease.

John Calsbeek
Technically it's alloc that creates the object, and thus requires a release, not init.
smorgan
Thanks, good catch.
John Calsbeek
Yeah I noticed that too. Thanks though. I'm really starting to appreciate garbage collection in other languages now.
Mk12
Objective-C does have garbage collection, but it doesn't exist on the iPhone because it's more computationally intensive and it would have a (minor?) impact on performance and battery life.
John Calsbeek
That's the technical side of not having memory management on the iPhone - the other side is that it forces developers to write code that is memory conscious and efficient. Those who don't flag up more obviously during review and get rejected.
Jasarien