问题
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).
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/6188387/uiviewcontroller-init-vs-initwithnibnamebundle