iosawakefromnib

When does awakeFromNib get called?


Does awakeFromNib get called right after viewController is allocated and initialized? At what precise point does the awakeFromNib of a view controller get called? From my debugging session, I see that awakeFromNib for the rootViewController doesn't get called until [self.window makeKeyAndVisible] is executed.


Solution

  • 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.

    EDIT: A detailed recount of events:

    During the instantiation process, each object in the archive is unarchived and then initialized with the method befitting its type. Cocoa views (and custom views that can be customized using an associated Interface Builder palette) are initialized using their initWithCoder: method. Custom views are initialized using their initWithFrame: method. Custom classes that have been instantiated in the nib are initialized using their init method.

    Once all objects have been instantiated and initialized from the archive, the nib loading code attempts to reestablish the connections between each object’s outlets and the corresponding target objects. If your custom objects have outlets, an NSNib object attempts to reestablish any connections you created in Interface Builder. It starts by trying to establish the connections using your object’s own methods first. For each outlet that needs a connection, the NSNib object looks for a method of the form setOutletName: in your object. If that method exists, the NSNib object calls it, passing the target object as a parameter. If you did not define a setter method with that exact name, the NSNib object searches the object for an instance variable (of type IBOutlet id) with the corresponding outlet name and tries to set its value directly. If an instance variable with the correct name cannot be found, initialization of that connection does not occur. Finally, after all the objects are fully initialized, each receives an awakeFromNib message.

    Source

    EDIT 2: This doesn't apply to view controllers loaded from storyboards.