Thursday, February 11, 2010

DevTip: Improving responsiveness of tab-based view controllers

I recently noticed a behavior difference between two different apps I had developed which both used UITabBarControllers. In one app, pressing each tab would immediately display the associated view controller’s views. In the other app, the first time a different tab was pressed, there would be a noticeable delay before the view controller’s view was displayed. After one time pressing each tab, however, then the response time was immediate for each tab.

When it comes to view controllers created from NIB files, the iPhone conserves memory by automatically loading and unloading them when necessary. So, when your app first launches, even if your view controllers are assigned to IBOutlet variables, their underlying views have not yet been created unless there is an immediate need for them.

In the case of my two different apps, in the one that had all its tabs being immediately responsive, it turns out I was doing some preliminary access to the view controllers views in my applicationDidFinishLaunching: method. Simply accessing the underlying view of the view controller will cause it to be loaded from it’s NIB file.

The benefit of doing this is each view controller will be initially loaded into memory when the app launches. This in turn will give better responsiveness to the view controllers being displayed when you initially press a tab.

The drawback is a slightly longer startup time for the app and you are now using more memory. Also, there is no guarantee that each of the view controllers will remain in memory. The iPhone OS may decide to unload one or more of them if memory conditions warrant it. But, if you have fairly complex views in a view controller and want to increase the likelihood the view will be immediately ready for display when a tab is pressed, using this technique will help.

All content copyright © 2009  Brian Stormont, unless otherwise noted.   All rights reserved.