UIViewController init vs initWithNibName:bundle:

2019-05-01 00:59发布

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

3条回答
Lonely孤独者°
2楼-- · 2019-05-01 01:20

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.

查看更多
3楼-- · 2019-05-01 01:24

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.

查看更多
Ridiculous、
4楼-- · 2019-05-01 01:26

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

查看更多
登录 后发表回答