views:

111

answers:

1

In objective-c, I understand that you need to release anything you init/retain/copy. Do I need to do that before a return statement? I'm wanting to understand calling release explicitly and not use autorelease.

-(void) someMethod
{
  AnotherClass* ac = [[AnotherClass alloc] init];
  if([ac somethingHappens]){
    // Do I need to release ac here?
    return;
  }
  [ac doSomethingElse];
  [ac release];
}

Thanks!

+1  A: 

Yes, you need to release your variables, however you exit from the method.

It's pretty straight-forward: when you init something the retain count is incremented. When you release it's decremented. When it reaches zero it's automatically deallocated (freed).

In your code above, you init the variable but if it follows the return route then the variables retain count never gets to zero and, therefore, is never deallocated.

Stephen Darlington
Actually, it's not when you `init` something, but when you `alloc` something. If your `init` method does not invoke `[super init]`, the retain count is still 1.
dreamlax
Oh! that's good to know. I've edited my post above.
Sam Washburn
@Stephen, thanks, that's what I needed to know. I understand it better now too.
Sam Washburn
@Sam Washburn: You were correct before you edited your question. The documentation for NSObject's `alloc` method explicitly states that it retains the object before returning it.
dreamlax
heh, ok. rolling back..
Sam Washburn