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
- 1

- 2,200
- 2
- 27
- 32
-
It is more common to use `awakeFromNib` in a UIView lifecycle. But the order you are looking for is `prepareForSegue`, `awakeFromNib`, `viewDidLoad` You can access outlets in awakeFromNib, but you should read the caveat that you need to first try to access your view controller's view. The so-called "hack" the poster of the other question was lamenting. It is safer and more standard to do view controller set up in `viewDidLoad`. – beyowulf May 10 '16 at 20:54
-
Thank you! So if we need fully initialised view and outlets we start awakeFromNib with [self view] – Vitya Shurapov May 12 '16 at 14:14
-
That's objective-c. In swift, you could say something like `print(self.view)`, which is somewhat nonsensical, and is why I recommend using `viewDidLoad`. – beyowulf May 12 '16 at 15:05
1 Answers
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:
Detail view controller is loaded from its nib. If the storyboard scene contains other top-level objects, these are also loaded.
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.Master view controller receives
prepareForSegue
with the segue pointing at the detail view controller.Segue asks navigation controller to push detail view controller.
Navigation controller asks detail view controller for its view, to add to the navigation controller's view hierarchy.
Detail view controller loads its view hierarchy nib. This connects the detail view controller's outlets to its view hierarchy.
All objects in the view hierarchy receive
awakeFromNib
.Detail view controller receives
viewDidLoad
.

- 1
- 1

- 375,296
- 67
- 796
- 848