I have an app that was crashing (in iOS 6 only) when the app was loaded with the following error:
Application windows are expected to have a root view controller at the end of application launch
*** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'A view can only be associated with at most one view controller at a time!
View <UITableView: 0xc21a800; frame = (0 20; 320 460); clipsToBounds = YES; opaque = NO; autoresize = W+H; gestureRecognizers = <NSArray: 0xbfb9d50>; layer = <CALayer: 0xbfb9720>; contentOffset: {0, 0}> is associated with <RootViewController: 0xbfbbb40>. Clear this association before associating this view with <RootViewController: 0xbfac010>.'
My applicationDidFinishLaunchingWithOptions looks like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
// Add root nav controller below everything else
RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStyleGrouped];
rootViewController.title = @"My App";
NSArray *sectionNames = [NSArray arrayWithObjects:@"Sec 1", @"Sec 2", @"Sec 3", nil];
rootViewController.sectionNames = sectionNames;
UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.navigationController = aNavigationController;
if ([self.window respondsToSelector:@selector(setRootViewController:)]) {
self.window.rootViewController = aNavigationController;
} else {
[self.window addSubview:aNavigationController.view];
}
// Add fake loading image
NSString* imageName = @"Default-Portrait.png";
theImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
theImageView.frame = CGRectMake(0,0,320,480);
[self.window addSubview:theImageView];
return YES;
}
RootViewController is just a subclass of UITableViewController with nothing interesting in it other than this:
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.delegate = self;
self.tableView.allowsSelection = YES;
self.userDefaults = [NSUserDefaults standardUserDefaults];
}
I have a .xib file for it but am not using it for initialization and this error is there whether that file exists or not.
Astoundingly, the error goes away when I add this to RootViewController:
- (void)loadView {
[super loadView];
}
It's [super loadView] that fixes the problem, and I shouldn't even be calling that. Why??