awakeFromNib vs Outlets - Do the outlets and segues set when we call awakeFromNib

411 Views Asked by At

I'm trying to understand a view controller's lifecycle and I've read a few contradictory statements about awakeFromNib. The docs say that all outlets should be set in awakeFromNib but I see that it's not always true. What is the call's order between awakeFromNib, prepareForSegue and when do the outlets become available?

1

There are 1 best solutions below

0
On BEST ANSWER

Your view controller and its view hierarchy are loaded from separate nib files at runtime. Outlets to the view hierarchy aren't connected until the view hierarchy is loaded, which happens after the view controller is loaded. (I have explained this in more depth in this answer.)

Let's say you have a “master” view controller in a navigation controller. The master view controller performs a segue to push a “detail” view controller. Here's the order of events:

  1. Detail view controller is loaded from its nib. If the storyboard scene contains other top-level objects, these are also loaded.

  2. Detail view controller receives awakeFromNib: detail view controller's outlets to other top-level objects in the scene are connected, but outlets to the view hierarchy are not.

  3. Master view controller receives prepareForSegue with the segue pointing at the detail view controller.

  4. Segue asks navigation controller to push detail view controller.

  5. Navigation controller asks detail view controller for its view, to add to the navigation controller's view hierarchy.

  6. Detail view controller loads its view hierarchy nib. This connects the detail view controller's outlets to its view hierarchy.

  7. All objects in the view hierarchy receive awakeFromNib.

  8. Detail view controller receives viewDidLoad.