Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITabbarcontroller in IOS5 throws UIViewControllerHierarchyInconsistency exception

I have the following code for the 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;

This code runs fine on IOS4. I tried it on IOS5 beta and get the following error when tapping on a 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>'
like image 451
user691219 Avatar asked Jun 08 '11 13:06

user691219


2 Answers

replace:

self.view = tabBarController.view;

with:

[self.view addSubview:tabBarController.view];

This will also be backwards compatible with IOS3&4.

like image 145
Joe Coder Avatar answered Nov 09 '22 23:11

Joe Coder


Had the same pattern (and problem) in my code. Joe's solution didn't work for me. Looking at the snippet, I'm guessing that you derive a class from UIViewController to allow you to customize something.

The thing to do here, and it is quite simple, is to derive from UITabBarController rather than UIViewController, don't create tabBarController, and anywhere you reference tabBarController, substitute self.

5 minutes and you're no longer throwing the inconsistency exception and you remain backwards compatible with iOS 4. You can still do all of your customization in your derived class (monkeying with the nav controller, etc).

If you have built a complex derivation of UIViewController you need to use, this could be more work.

One small gotcha - if you override LoadView, you'll find that it gets called during the init for the UITabBarController. Makes it hard to set members prior to LoadView, so you may need to split up your initialization.

Good luck!

like image 28
Matt Avatar answered Nov 10 '22 01:11

Matt