Skip to content

TIL: UIViewController.init() might initialize a xib

It is all in the documentation, both in the UIViewController Class Reference, and in the comments in the class header. It also makes sense, but today I spent a couple of hours debugging a weird crash, due to this.

So this is something I think I won’t forget in a long time.

When initializing a view controller passing nil as a nib, the view controller will attempt to load a nib whose name is the as same as the view controller’s class. That’s what the UIViewController header clearly states:

If you
invoke this method with a nil nib name, then this class’ -loadView method will attempt to load a NIB whose
name is the same as your view controller’s class. If no such NIB in fact exists then you must either call
-setView: before -view is invoked, or override the -loadView method to set up your views programatically

But there is more. According to the UIViewController class reference:

If you use a nib file to store your view controller’€™s view, it is recommended that you specify that nib file explicitly when initializing your view controller. However, if you do not specify a nib name, and do not override the loadView method in your custom subclass, the view controller searches for a nib file using other means. Specifically, it looks for a nib file with an appropriate name (without the .nib extension) and loads that nib file whenever its view is requested. Specifically, it looks (in order) for a nib file with one of the following names:

If the view controller class name ends with the word ‘Controller’, as in MyViewController, it looks for a nib file whose name matches the class name without the word ‘€œController’, as in MyView.nib.

It looks for a nib file whose name matches the name of the view controller class. For example, if the class name is MyViewController, it looks for a MyViewController.nib file.

And that’s exactly what happened to me earlier today. I was initializing a view controller like this:

While also having in the project a completely unrelated xib, named AddContactView. Unrelated, like in “AddContactViewController does not use AddContactView.xib at all. Nothing. Zero.”

So my app was crashing, throwing an assertion that kindly reminded me that AddContactView did not have any owner properly setup.

Well, there is a reason for that.

Remember, read your docs! 💁

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *