问题
I'm trying to load a NIB based on a variable I get from my settings file. This is the code:
//select the right nib name
NSString *nibVar = [nibs objectForKey:@"controller"];
// create the view controller from the selected nib name
UIViewController *aController = [[UIViewController alloc] initWithNibName:nibVar bundle:nil];
aController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:aController animated:YES];
[aController release];
This unfortunately does not work.
Any ideas here?
Thanks
回答1:
You cannot instantiate "UIViewController" with arbitrary NIBs, you have to instantiate "[whatever your custom view controller class is]" with the NIB for that class.
It's crashing because it's trying to access properties that don't exist in UIViewController.
If you want to do this kind of dynamic view-controller loading, you need to do a bit more work, and use the special Class class method that lets you instantiate an object using a string for the class name, instead of hard-coded.
Sometehing like:
Class viewControllerClass = NSClassFromString( nibVar );
UIViewController* aController = (UIViewController*) [[viewControllerClass alloc] initWithNibName:nibVar bundle:nil];
回答2:
Make sure the NIB name is correct and does not include the xib extension. It is also case sensitive.
来源:https://stackoverflow.com/questions/5417889/load-nib-from-variable