Tuesday, July 14, 2009

UIViewControllers - What's happening to memory?

So I've been using UIViewControllers in my iphone apps and when I use the Instruments application's activity monitor, I noticed that iphone's memory kept increasing when I pushed a UIViewController then pop it to come back to the main screen.

Here's the problem I found.

if (detailViewController == nil) {
detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
}
[self.navigationController pushViewController:controller animated:YES];


The above is how I pushed a UIViewController. This is used by many examples in the iphone developer's portal website.
The examples are correct ONLY if you are planning to re-use that detailViewController sometime later.
The above method of pushing a view controller will not release the view controller and stay in the memory until the app is closed.

Now, if you need to have the detailViewController release its memory, you have to push the view controller in this way.

DetailViewController* detailViewController = [[DetailViewController alloc] init];
[self.navigationController pushViewController: detailViewController animated:YES];
[detailViewController release];

You should do it this way when you need to release memory of the pushed view controller and do not want that detailViewController occupying memory for the duration of your app.

How do you know when to re-use a view controller vs when not to?
Typically, if you are using the same visual elements and only changing the data with new data, you should re-use the view controller. (ie. not release the view controller)
Otherwise, if you are changing more than just data (such as the visual elements programmatically) then you should release the view controller and push a new view controller.


Here's a snapshot of the Instruments -> activity monitor showing my app using over 10MB of memory. There is only a limited amount of memory that's available for your app to use. So you have to closely monitor how much memory you app is using and whether all allocations are deallocated properly. On one app, I have seen its real memory usage go up to 57MB before crashing. On a different app, I've seen it go up until 35MB before crashing. Once the phone has not enough memory, the app simply crashes (effectively closing the app).

And if you are playing music while running an app and the app is increasingly using up memory, I noticed that the music player closes first to make available some more memory to the app.

-도시

No comments:

Post a Comment