问题
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
回答1:
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.
回答2:
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.
回答3:
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];
回答4:
If want to try, you should try this
id temp = [self.navigationController.viewControllers objectAtIndex:1];
[self.navigationController popToViewController:temp animated:YES];
you'll be navigated to any other previous ViewController that are available in the stack.
来源:https://stackoverflow.com/questions/3559230/does-pushviewcontroller-retain-the-controller