Objective-c – UIViewController subclass init not called when loading from nib

interface-buildermodel-view-controllernibobjective cuikit

I tried overriding the default initWithNibName designated initializer of a UIViewController subclass like so:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}

I have also included its definition in the header file. However, when my Application Delegate nib loads the viewcontroller, the initializer is not invoked, only -viewDidLoad.

How does the nib magic instantiate my view controller then? Why do all the XCode templates state

// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

Is it correct my initWithNibName isn't called when the viewcontroller is loaded form another nib?

Best Answer

You need to put your initialization code inside the awakeFromNib method for it to be run when loaded from Nib. The Nib file contains an archived version of the objects that it contains, so in principle, they do not need to be initialized again.