views:

89

answers:

3

I am struggling to find out if pushViewController retains the controller, currently I have the following code (which works) ...

ColorController *colorController = [[ColorController alloc] initWithNibName:nibColor bundle:nil];
[[self navigationController] pushViewController:colorController animated:YES];
[colorController release];

but am considering removing the release and adding an autorelease ...

ColorController *colorController = [[[ColorController alloc] initWithNibName:nibColor bundle:nil] autorelease];
[[self navigationController] pushViewController:colorController animated:YES];

Much appreciated

Gary

+4  A: 

This does nothing...

ColorController *colorController = [[ColorController alloc] initWithNibName:nibColor bundle:nil];
[[[self navigationController] pushViewController:colorController animated:YES] autorelease];

You are autoreleasing the return value of pushViewController:animated:, which is void.

Your first snippet is valid, and correct. pushViewController: does indeed retain the controller that is pushed.

Edit: In your updated code, there is little difference between the two samples. Both maintain proper retain counts. However, it is a "best practice" to avoid using autoRelease unless necessary (especially in a memory sensitive area, like the iPhone). This helps your application to maintain a more predictable and manageable memory footprint.

Jerry Jones
Thank you, sorry again for dropping the autorelease on the wrong line. Just what I was after.
fuzzygoat
Typos happen, just wanted to make sure it wasn't intentional! haha.
Jerry Jones
It's also a best practice to prefer autorelease to avoid coding errors. Which do you choose?Well, if Instruments tells you that autorelease is taking up a significant amount of CPU or memory, then sure you can use explicit release calls. But this is very unlikely.
Mike Weller
A: 

It sure does. Anytime you give one object to another SDK object like this, it will be retained. Though that second line isn't autoreleasing what you think. Usually you want the autorelease on the same line as the init for clarity sake.

ColorController *colorController = [[[ColorController alloc] initWithNibName:nibColor bundle:nil] autorelease];
[[self navigationController] pushViewController:colorController animated:YES];
Squeegy
+2  A: 

Yes, the view controller is retained.

There isn't a huge difference between the two code blocks you posted (at least the version I'm looking at -- other people probably saw an earlier version with a misplaced call to autorelease). You could use either one. It's a matter of style.

Shaggy Frog
Thank you Shaggy Frog, much appreciated.
fuzzygoat