Search code examples
iphoneobjective-cpropertiesobject-initialization

What's the point of this in objective-c


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

Why is it always done that way? Why not

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

Solution

  • 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.