Search code examples
iosinterface-builderxib

When does a view outlet have to be set?


I have read through other answers on how to fix "view outlet was not set" exceptions, and understand how to set the file owner and view outlet. However, I can't understand when/why that exception is raised. How come I can get away with this, and it's not an issue?

override func viewDidLoad() {
    super.viewDidLoad()

    let viewNib = UINib(nibName: "MyView", bundle: nil)
    let myView = viewNib.instantiate(withOwner: nil, options: nil).first as! MyView

    self.view = myView
}

The MyView class is initialized with a nib, and the nib file itself does not have a file owner set, nor a view outlet, and it's fine. But other times, this doesn't work. I've tried to reproduce a specific case identifying when the exception is and isn't raised, but haven't been able to pin it down.


Solution

  • Alladinian's comment helped. The relevant docs are from the loadView() method:

    A view controller has an associated nib file if the nibName property returns a non-nil value, which occurs if the view controller was instantiated from a storyboard, if you explicitly assigned it a nib file using the init(nibName:bundle:) method, or if iOS finds a nib file in the app bundle with a name based on the view controller's class name.

    For example, I made a nib with the name 'DuckView', and a view controller with the name 'DuckViewController', and Xcode automatically associated the two and expected the view outlet to be set. If the view outlet is not set, AND loadView() is not overridden, the exception is raised. Conversely, if either the view outlet IS set OR the loadView() method is implemented, it runs fine.