简体   繁体   中英

Crash in the didFinishLaunchingWithOptions method

self.rootViewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
[self.window addSubview:self.rootViewController.view];    //App will not crash without this line

self.navigationController = [[UINavigationController alloc] initWithRootViewController: self.rootViewController];
[self.window addSubview:self.navigationController.view];

I run it in the simulator and it crash, why?

Error message:

Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', 
reason: 'adding a root view controller <RootViewController: 0x6871620> as a child of 
view controller:<UINavigationController: 0x6a86dc0>'

still have no idea

You are not specifying your problem clearly,so please add error message what you got on the console.Without error message we are unable to tell where the problem occur.Any how it crashes due to nibfile name,you specifying nib file name as nil.Please specify nib file name. Try this code once.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        // Override point for customization after application launch.
        self.rootViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
        self.navigationController=[[UINavigationController alloc] initWithRootViewController:self.rootViewController];
        self.window.rootViewController = self.navigationController;
     //   [self.window addSubview:navigationController.view];
        [self.window makeKeyAndVisible];
        return YES;
    }

I hope this code will solve your problem

yours logic is wrong. Either add rootViewController or add navigationController as window's subview. You can't add two viewcontrollers at the same time. Here your navigationController will overwrite your rootviewcontroller. If possible then add your rootviewcontroller into navigationController or add navigationController into rootviewcontroller

Since You are setting RootViewController nib name to nil i hope you are managing your view in RootViewController.m inside method -(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil or some other way.

to fix your error message you have given, change your posted code following way

self.rootViewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController: self.rootViewController];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];

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