I’m just wondering about the following 2 approaches.
First:
SomeViewController *someViewController = [[SomeViewController alloc] init];
[self.navigationController pushViewController:someViewController animated:YES];
[someViewController release];
Second:
SomeViewController *someViewController = [[SomeViewController alloc] init];
self.iVarViewController = someViewController;
[someViewController release];
[self.navigationController pushViewController:self.iVarVierController animated:YES];
Is it OK to take the first approach, or should one always try to adopt the second? What exactly is wrong with the first approach? When ‘someViewController’ is pushed on to the stack, is its retain count incremented and therefore it is never fully released? Which is why you might want to assign it to a property as in the second approach? But in the second approach, you can’t be certain when it will be released.
I’ve read a similar post but I’m still a bit unsure so thought I’d ask even more simply.
The consequences of the two approaches are slightly different. In the first, the instance of
SomeViewControllerand its view will be deallocated as soon as the instance is popped. In the second, the instance ofSomeViewControllerwill kept in memory until it is replaced by a new one (self.iVarViewController = someViewController).The second approach might make sense if the first view controller needs to send messages to the second one (such as to obtain changed property values) after the second controller gets popped. In this case though, you’d have to ask yourself whether it makes sense to recreate the object each time, rather than just reusing the instance stored in the property (
ivarViewControllerin your example).Whether one is better than the other depends on a combination of the expected usage patterns for this part of your app, and the performance characteristics of the second controller and its view. (For example, how much memory do the objects consume, and how frequently do users typically switch back and forth between two controllers?)