Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Releasing local variables before return?

Tags:

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!

like image 463
Sam Washburn Avatar asked Feb 17 '10 20:02

Sam Washburn


1 Answers

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.

like image 152
Stephen Darlington Avatar answered Oct 19 '22 23:10

Stephen Darlington