IOS5中的UITabbarcontroller抛出UIViewControllerHierarchyInconsistency异常

时间:2011-06-08 13:47:56

标签: objective-c uitabbarcontroller ios5

我有以下UITabbarcontroller的代码:

NSMutableArray *arr = [[NSMutableArray alloc] init];
tabBarController = [[UITabBarController alloc] init];

FirstViewController *firstview = [[FirstViewController alloc] init];
[tabBarControllerViews addObject:firstview];
[firstview release];

 SecondViewController *secondview = [[SecondViewController alloc] init];
[tabBarControllerViews addObject:secondview];
[secondview release];

[tabBarController setViewControllers:arr animated:YES];
[arr release];

self.view = tabBarController.view;

此代码在IOS4上运行良好。我在IOS5测试版上尝试了它,并在点击UITabbarItem时出现以下错误:

*** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency',
reason: 'child view controller:<FirstViewController: 0x6e03be0> should have parent view
controller:<MainViewController: 0x6816d20> but actual parent is:<UITabBarController: 0x6b0c110>'

4 个答案:

答案 0 :(得分:23)

取代:

self.view = tabBarController.view;

使用:

[self.view addSubview:tabBarController.view];

这也将向后兼容IOS3&amp; 4。

答案 1 :(得分:6)

我的代码中有相同的模式(和问题)。 Joe的解决方案对我不起作用。看一下片段,我猜你从UIViewController派生了一个类,允许你自定义一些东西。

这里要做的事情很简单,就是从UITabBarController而不是UIViewController派生,不要创建tabBarController,并且在任何你引用tabBarController的地方,替换self。

5分钟,你不再抛出不一致异常,你仍然向后兼容iOS 4.您仍然可以在派生类中进行所有自定义(使用导航控制器等等)。

如果您构建了一个需要使用的UIViewController的复杂派生,那么这可能会更有用。

一个小问题 - 如果你重写LoadView,你会发现它在UITabBarController的init期间被调用。在LoadView之前设置成员很困难,因此您可能需要拆分初始化。

祝你好运!

答案 2 :(得分:0)

您无法推送或呈现UITabbarViewController。你的第一视图控制器是UITabBarController吗?

答案 3 :(得分:0)

我在同样的问题上挣扎。

当您创建新的Master-Detail应用程序(没有故事板)时,您可以从AppDelegate.m中看到以下代码。

 MasterViewController *masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:masterViewController];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];

“不要依赖MainWindow” 从您自己的ViewController开始,并将其设置为委托。 并且不要忘记从MainWindow.xib取消链接视图,否则视图将被调用2次。