Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 651
Fr4ncis Avatar asked May 31 '11 13:05

Fr4ncis


3 Answers

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.

like image 121
Tony Avatar answered Nov 15 '22 08:11

Tony


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.

like image 30
pkananen Avatar answered Nov 15 '22 09:11

pkananen


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

  • You can see that this is the designated initializer in its parent class UIViewController docs.
  • You can learn more about designated initializers in Apple's docs
  • A related SO question where I learned this.
like image 25
Cody A. Ray Avatar answered Nov 15 '22 07:11

Cody A. Ray