Wat? iOS 5? Are you serious?

Yea, I know that your shining iPhone 5 is running the latest iOS 7 beta nowdays. But still there are customers having some app we wrote and sticking on old devices. Especially considering that the booming market of jailbroken devices in China, dropping support for legacy OS is not a easy decision anyway.

Long story short. Recently we found some UIViewController subclasses in our app don't unload their views when they received a memory warning. After diagnosis, it turns out that only some of view controllers instantiated without a XIB file behave abnormally.

UIViewController's view loading mechanism is well documented in the View Controller Programming Guide for iOS. It instantiates its view in loadView method either by loading it from a associated XIB/storyboard file or creating it programmatically. Actually there are three different cases:

  • view controller associated with a XIB/storyboard file
  • view controller without a XIB/storyboard file but overriding loadView method to create a view programmatically
  • view controller without a XIB/storyboard file and not overriding loadView method

In the third case, UIViewController will create an empty UIView object and assigned it to its view property. But for some unknown reason, it doesn't unload it when received a memory warning. Therefore your viewDidUnload method will certainly not get called. This is a weird and undocumented behavior.

After overriding loadView method to create and set view, all our view controllers behave correctly on iOS 5 now.