Question

what are best pratices to reuse UIViewControllers? In many apps (including Apple's own examples: e.g. SQLiteBooks), UIViewControllers are allocated and initialized everytime, a UIViewController is pushed to the stack. This increases the use of memory with every new controller, because the objects stay in memory and aren't used again.

How to make it better?

Was it helpful?

Solution

This is what I do when creating a new viewcontroller and the memory is released when the view is removed from the window

MyViewController *mvc = [[[MyViewController alloc] initWithNibName:@"MyView" bundle:nil] autorelease];
[[self navigationController] pushViewController:mvc animated:YES];

OTHER TIPS

This increases the use of memory with every new controller, because the objects stays in the memory and aren't used again.

It should be released when the stack is popped though, as long as you have not got something else holding on to it. Check your dealloc methods are getting called.

Also if it is pushed to the stack, then you need to keep it around at least until it is popped (which automatically happens if you follow the standard patterns). So it is used again.

So following the standard pattern should already keep your memory usage as small as you can get away with.

Do you actually have a memory issue that you are trying to address or is this a case of premature optimization? I would say that unless there is a specific resource issue then the best practice would be to follow the standard view controller patterns.

Put a breakpoint in your view controller's dealloc function, and make sure it is called when you remove the view controller from the window. The memory shouldn't keep building up. If you're properly creating and autoreleasing your controllers (as LostInTransit shows above), the memory for each controller should be released when it is removed.

If you see that dealloc is not getting called, it means that somewhere in the app a reference to the view controller still exists.

Don't forget that a View Controller is not your view.

Views held by a view controller can unload, so view controllers themselves are very lightweight. If you want to keep the footprint really light you could nullify any other data the controller has allocated in viewDidUnload (mostly called when there's a memory warning - it's a 3.0 only thing though).

As noted mostly view controllers will be deallocated when you leave them (hit back) so there aren't generally that any hanging around anyway. But sometimes I find it handy to leave a reference around if I want to re-open that view in the same state the user left it (does not work between app launches).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top