ylliX - Online Advertising Network

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:

let vc = new MyNewController()
self.present(vc, animated: true, completion: nil)

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

init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
init?(coder aDecoder: NSCoder)

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

guard let vc = self.storyboard?.instantiateViewController(withIdentifier: "MyNewController") as? MyNewController else { return }
self.present(vc, animated: true, completion: nil)

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