简体   繁体   中英

init root viewcontroller causes crash

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM