IBOutlet becomes nil in viewDidLoad function of your UIViewController?

This is a bit scary for all beginners. You made your pretty view in Interface Builder, attached UIViewController and trying to:

But what happens next? Trying to reach any IBOutlet in viewDidLoad() causes your app to crash. They are not marked as optionals so why? And how to prevent?

So first WHY this happens – if you are creating view controller like above, you are calling default initializer of NSObject, because UIViewController does not have func init(). NSObject does. And what have UIViewController? Only

So how to prevent? If you created your view in Interface Builder, just rewrite your code to:

But beware – this is required only if you are using Storyboard, when view is created as XIB it will work as shown in first code block.

Leave a Reply