Proper use of loadView and viewDidLoad with UIViewController without nibs/xibs

As the documentation says, you should not call these methods yourself.

How this is meant to work is that UIKit’s code will call your loadView method if and when it actually needs to present that controller’s view hierarchy on screen.

Specifically, if any code attempts to read your view property on your view controller, and that property is nil, then UIViewController’s code will call the loadView method. If you don’t implement loadView yourself, then the default implementation will fall back to attempting to load the view hierarchy from the nib.

This all happens automatically when you attempt to present your view controller and the view is nil. (This can happen multiple times while your app is running if your view controller has to unload its view in response to memory pressure, another behavior you get for ‘free’ and that you don’t want to call yourself)

If these methods are not being called in your view controller, then there must be something wrong with how you are presenting this view controller, which is preventing the framework code in UIViewController from calling these methods. Post that code and someone can help you figure out that bug.

Before you attempt to fix that bug, though, you should remove these from your code:

[self loadView]
[self viewDidLoad]

And then in your own implementation of viewDidLoad, you will want to call the superclass’ implementation with [super viewDidLoad]

Remember that in loadView your only responsibility to set self.view to some valid view. That’s it. UIKit code will then see that and call viewDidLoad for you.

Hope that helps.

Leave a Comment