Fr4ncis
Fr4ncis

Reputation: 1387

UIViewController init vs initWithNibName:bundle:

In my app I am pushing a view controller (a UITableViewController) that has also a property/outlet referencing a UITableViewCell. It appears that creating the controller with:

PreferencesController *pController = [[PreferencesController alloc] init];

doesn't create the object for the UITableViewCell in the xib file, thus the outlet is null, thus the table loading generates an exception. I solved this with:

PreferencesController *pController = [[PreferencesController alloc] initWithNibName:@"PreferencesController" bundle:nil];

but I didn't really get why it worked, as from documentation it seems that init should be sufficient to load the related nib file (PreferencesController.xib).

Upvotes: 5

Views: 11780

Answers (3)

Cody A. Ray
Cody A. Ray

Reputation: 6017

You have to override initWithNibName:bundle: instead of init because this is the "designated initializer". When you load this from a Nib file, this is the creator message being called.

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

Resources

Upvotes: 1

Tony
Tony

Reputation: 3478

There seems to be something magical about the name PreferencesController. I just had the exact same problem. Renaming my class (and xib) to something else solved the problem.

Upvotes: 4

pkananen
pkananen

Reputation: 1325

Edit: I was incorrect, nib files should load automatically with alloc init if they are named the same as the controller.

What is your File's Owner in Interface Builder? The default behavior can be modified by changing this value.

Upvotes: 3

Related Questions