I created a new Xcode project with a view-based app template. In the .m of the view controller I overwrote this:
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
NSLog(@"initWithNibName...");
}
return self;
}
- (id)init {
NSLog(@"initWithNibName...");
return [super init];
}
However, I never get that NSLog. That’s also my experience from other projects. This method is never called. Not even -init from NSObject.
The View Controller is created inside the XIB file. How’s that possible, that the Nib Loading System instantiates this class without any kind of initialization?
Why? And what’s the alternative instead of -loadView and -viewDidLoad?
Another great reason to stay far away from XIB files?
From the iOS Resource Programming Guide
Think of it this way: the designated initializer is called when your view controller is first created in Interface Builder. Then, when you save the nib file, the view controller instance is stored in the file. Later, when the nib is loaded, the instance is recreated from the nib.
Since it’s being recreated rather than created for the first time, a different initialization method is used. This method (
-initWithCoder:) restores the object’s state using values from the nib file, which can include settings for properties beyond those that were set by the designated initializer. This mechanism relies on theNSCodingprotocol, which allows it to work generically for many different classes.