tags:

views:

27

answers:

3

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?

+1  A: 

You can use - awakeFromNib for this. The init is only called if you do so in code.

Sander Backus
thanks for that hint! but anyways, how can it be that the Nib Loader creates instances of this class without doing any init?
BugAlert
All objects that are loaded from a NIB (or another NSCoding archive) are initialized with `-initWithCoder:`.
Ole Begemann
makes sense, but why is -init never called? it's the designated initializer of NSObject...
BugAlert
A: 

Have you set your MainWindow's delegate as your appDelegate..? Implement UIApplicationDelegate in your AppDelegate and in the applicationDidFinishLaunching Methode,try initWithNibName. That will do the trick.

Aji
+1  A: 

From the iOS Resource Programming Guide

In iPhone OS, any object that conforms to the NSCoding protocol is initialized using the initWithCoder: method. This includes all subclasses of UIView and UIViewController whether they are part of the default Interface Builder library or custom classes you define.

Think of it this way: the designated initializer is called 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 for more properties than those that can be set by the designated initializer. This mechanism relies on the NSCoding protocol, which allows it to work generically for many different classes.

jlehr