Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awakeFromNib, outlets and storyboards: is the documentation wrong?

Tags:

According to the NSObject UIKit Additions Reference, outlet variables should be set by the time awakeFromNib is called (emphasis all mine):

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

...

Important: Because the order in which objects are instantiated from an archive is not guaranteed, your initialization methods should not send messages to other objects in the hierarchy. Messages to other objects can be sent safely from within an awakeFromNib method.

Typically, you implement awakeFromNib for objects that require additional set up that cannot be done at design time. For example, you might use this method to customize the default configuration of any controls to match user preferences or the values in other controls. You might also use it to restore individual controls to some previous state of your application.

However, this does not match my tests, at least using Storyboards. The results of the following test seem to contradict the documentation:

  • Create a new Single View Application in Xcode.
  • Drag a second ViewController onto the storyboard.
  • Give the first ViewController a button, and create a modal segue from that button that displays the second ViewController.
  • Create a ViewController class file for the second ViewController.
  • Create a label on the second ViewController on the storyboard and create an outlet called someLabel from it to the corresponding ViewController class.
  • Add the following awakeFromNib implementation to the second ViewController:

.

- (void) awakeFromNib {     [super awakeFromNib];     if (self.someLabel == nil) {         NSLog(@"someLabel property is nil");     }     else {         NSLog(@"someLabel property is not nil");     }          if (_someLabel == nil) {         NSLog(@"_someLabel is nil");     }     else {         NSLog(@"_someLabel is not nil");     } } 
  • Run the app in the simulator and click the button.

When I do this, I observe the following logged:

2013-07-01 09:24:35.755 test[498:c07] someLabel property is nil 2013-07-01 09:24:35.758 test[498:c07] _someLabel is nil 

As a consequence of this behaviour, when I need my ViewControllers to have some initialisation logic that involves their outlets, I need to use a hack like the one proposed in the answer here in order to be able to use the outlets. If I'm understanding the documentation correctly, the fact that I'm forced to use this hack is a bug in the UIKit behaviour, and I ought to be able to put that initialisation in awakeFromNib and simply use the outlets without any hacks.

I can't find any other mention of this issue on the internet, though, which seems odd given what a fundamentally important bit of functionality this appears (to me) to be. I've also never used actual nib files, only storyboards, so I'm missing some perspective on this, and the documentation on this stuff is verbose and difficult enough that as a newbie to iOS I'm not confident that I've understood correctly. Is this a genuine UIKit bug, or have I misunderstood the documentation in some way - perhaps this method isn't even meant to be used in conjunction with storyboards?

like image 484
Mark Amery Avatar asked Jul 01 '13 08:07

Mark Amery


People also ask

When to use awakeFromNib?

Typically, you implement awakeFromNib for objects that require additional set up that cannot be done at design time. For example, you might use this method to customize the default configuration of any controls to match user preferences or the values in other controls.

When awakeFromNib is called?

awakeFromNib gets called after the view and its subviews were allocated and initialized. It is guaranteed that the view will have all its outlet instance variables set.


2 Answers

Short Answer

Your view controller and its view hierarchy are loaded from separate nib files at runtime.

Your view controller is loaded first and receives awakeFromNib when its nib is loaded, but its view hierarchy nib hasn't been loaded yet, so in awakeFromNib you shouldn't assume any outlets to the view hierarchy have been set yet.

Your view controller receives viewDidLoad after its view hierarchy nib has been loaded, so in viewDidLoad you can assume all outlets have been set.

Long Answer

When Xcode builds your app, it compiles your storyboard. The result is a package (a folder that Finder treats as a file) containing an Info.plist and a bunch of .nib files. Example from one of my projects:

:; pwd /Users/mayoff/Library/<snip>/Pinner.app/Base.lproj/Main.storyboardc :; ll total 80 drwxr-xr-x  10 mayoff  staff   340 May 11 22:13 ./ drwxr-xr-x   4 mayoff  staff   136 May 11 22:13 ../ -rw-r--r--   1 mayoff  staff  1700 May 11 22:13 AccountCollection.nib -rw-r--r--   1 mayoff  staff  1110 May 11 22:13 AccountEditor.nib -rw-r--r--   1 mayoff  staff  2999 May 11 22:13 BYZ-38-t0r-view-8bC-Xf-vdC.nib -rw-r--r--   1 mayoff  staff   439 May 11 22:13 Info.plist -rw-r--r--   1 mayoff  staff  7621 May 11 22:13 LqH-9K-CeF-view-OwT-Ts-HoG.nib -rw-r--r--   1 mayoff  staff  6570 May 11 22:13 OZq-QF-pn5-view-xSR-gK-reL.nib -rw-r--r--   1 mayoff  staff  2473 May 11 22:13 UINavigationController-ZKB-z3-xgf.nib -rw-r--r--   1 mayoff  staff   847 May 11 22:13 UIPageViewController-ufv-JN-y6U.nib 

The Info.plist maps the scene names in your storyboard to the corresponding nibs:

:; plutil -p Info.plist  {   "UIViewControllerIdentifiersToNibNames" => {     "AccountCollection" => "AccountCollection"     "UINavigationController-ZKB-z3-xgf" => "UINavigationController-ZKB-z3-xgf"     "UIPageViewController-ufv-JN-y6U" => "UIPageViewController-ufv-JN-y6U"     "AccountEditor" => "AccountEditor"   }   "UIStoryboardDesignatedEntryPointIdentifier" => "UINavigationController-ZKB-z3-xgf"   "UIStoryboardVersion" => 1 } 

A scene only shows up in this list if it has a storyboard ID, or a segue connects to it, or it is the initial scene.

The nib files list in Info.plist do not contain the view hierarchies of those view controllers. Each of those nib files contains the view controller of its scene and any other top-level objects in the scene, but not the view controller's view or any of its subviews.

A separate nib file contains the view hierarchy for the scene. The name of view hierarchy nib derived from the object IDs of the view controller and its top-level view. You can see the object ID of any object in your storyboard in the “Identity Inspector” in Xcode. For example, my “AccountCollection” scene's view controller's ID is BYZ-38-t0r and its view's ID is 8bC-Xf-vdC, so the view hierarchy for the scene is in file BYZ-38-t0r-view-8bC-Xf-vdC.nib. The scene nib file contains the name of its view hierarchy nib file:

:; strings - AccountCollection.nib |grep -e '-.*-' UIPageViewController-ufv-JN-y6U BYZ-38-t0r-view-8bC-Xf-vdC          <--------- UpstreamPlaceholder-5Hn-fK-fqQ UpstreamPlaceholder-8GL-mk-Rao q1g-aL-SLo.title 

If a scene doesn't have a view hierarchy, then there will just be a nib file for the view controller and no separate nib file for the view hierarchy. For example, a UIPageViewController scene doesn't have a view hierarchy in the storyboard so there's no view hierarchy nib corresponding to UIPageViewController-ufv-JN-y6U.nib.

So what does all this have to do with your question? Here's what: when your app loads a scene from the “storyboard”, it's loading the nib file containing the view controller (and other top-level objects). When the nib loader finishes loading that nib file, it sends awakeFromNib to all the objects it just loaded. This includes your view controller, but it does not include your views, because your views weren't in that nib file.

Later, when your view controller is asked for its view property, it loads the nib file containing its view hierarchy. The view controller passes itself to -[UINib instantiateWithOwner:options:] as the owner argument. This is how the nib loader can connect objects in the view hierarchy to the view controller's outlets and actions.

When the nib loader finishes loading the view hierarchy nib, it sends awakeFromNib to all the objects it just loaded. Since your view controller was not one of those objects, your view controller does not receive an awakeFromNib message at this time.

When instantiateWithOwner:options: returns, the view controller sends itself the viewDidLoad message. This is your opportunity to make changes to the view hierarchy.

like image 157
rob mayoff Avatar answered Sep 20 '22 04:09

rob mayoff


View controllers wait until their view is accessed to actually create their view. Since the button is in the view controller's view, it won't be instantiated yet.

like image 34
nevan king Avatar answered Sep 19 '22 04:09

nevan king