lockedscope
lockedscope

Reputation: 983

release or autorelease?

should i use release or autorelease for varSecondViewController?

-(IBAction)takeNextStep: (id) sender
{
    SecondViewController *varSecondViewController = [[SecondViewController alloc]     
       initWithNibName:@"SecondViewController" bundle:nil];
    [self.navigationController pushViewController:varSecondViewController animated:YES];
    [varSecondViewController release];
}

Upvotes: 3

Views: 402

Answers (3)

Brad
Brad

Reputation: 11505

My rule of thumb:

If you're going to use it, and then no longer need a reference to it, release it,

If you're going to pass it back to the caller (i.e. return it), autorelease it.

Upvotes: 12

Chuck
Chuck

Reputation: 237010

autorelease is just a release that's delayed until some time in the future, which is guaranteed to be at least the current call stack unless a caller has created its own autorelease pool. You generally use it when you need to release an object in order to follow the memory management guidelines, but that object might still be needed further up the call stack. In this case, you're not returning the view controller and have no intention of directly holding onto it any further, so there's no need for a delay. You can just release.

Upvotes: 6

Daniel A. White
Daniel A. White

Reputation: 190907

In this case, release makes the most sense.

Upvotes: 4

Related Questions