Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

init root viewcontroller causes crash

Tags:

ios

ios6

I used codes below to init a root view controller

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 

{

[window addSubview:rootViewController.view];
UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController: rootViewController  ];
}

it worked well on ios 4 about 2 years,ios5 1 years, there is no any problem when start to run the app but on ios6 it crashed and reported

* Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'adding a root view controller as a child of view controller:'

Welcome any comment

like image 378
arachide Avatar asked Oct 29 '25 05:10

arachide


2 Answers

'rootViewController' is already in your view hierarchy. Remove it from whatever other container its in (window.rootViewController ?) first (window.rootViewController = nil).

like image 72
David H Avatar answered Oct 30 '25 23:10

David H


In your code you are adding rootViewController's view to window then immediately trying to add rootViewController's view to the new UINavigationController. Instead try this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ...    

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    [window addSubview:nav.view];

    ...
}

or even better:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ...    

    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    window.rootViewController = nav;

    ...
}

The ... are there to show that these are incomplete examples of -application:didFinishLaunchingWithOptions:. You need to make sure you have included creating your UIWindow and calling -makeKeyAndVisible on it.

like image 29
Adam Swinden Avatar answered Oct 30 '25 23:10

Adam Swinden