init root viewcontroller导致崩溃

时间:2012-09-27 11:32:34

标签: ios ios6

我使用下面的代码来初始化根视图控制器

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

{

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

它在ios 4上运行良好约2年,ios5 1年,开始运行应用程序时没有任何问题 但在ios6上,它崩溃并报告

* 由于未捕获的异常'UIViewControllerHierarchyInconsistency'而终止应用程序,原因是:'将根视图控制器添加为视图控制器的子级:'

欢迎任何评论

2 个答案:

答案 0 :(得分:3)

'rootViewController'已经在您的视图层次结构中。首先从(window.rootViewController?)中的其他容器中删除它(window.rootViewController = nil)。

答案 1 :(得分:2)

在您的代码中,您将rootViewController的视图添加到窗口,然后立即尝试将rootViewController的视图添加到新的UINavigationController。相反,试试这个:

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

    ...    

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

    ...
}

甚至更好:

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

    ...    

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

    ...
}

......表明这些是-application:didFinishLaunchingWithOptions:的不完整示例。您需要确保已包含创建UIWindow并在其上调用-makeKeyAndVisible