Reputation: 1866
I am working on an iOS app, where-in i have a tabbar controller and respective view controllers. For each tab in tabbar controller set with an view controller. This setup is done in .xib file itself. But still, in the didFinishLaunchingWithOptions i am adding the below code as well to launch default view as second tab view when my app launches,
self.viewController = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];
[self.tabBarController setSelectedViewController:self.viewController]; // crash
What happens here is, its working fine on iOS 4 simulator and device, but the crash is happening in the second line of this code in iOS 5 simulator and device. We are trying to find out why it crashes only on iOS 5 devices/simulators, still couldn't be able conclude it. If the view controllers are already setup in .xib file itself, then i don't need to instantiate the object and do setup like this in didFinishLaunchingWithOptions from iOS5? What could the reason for this crash, please advise.
Thank you!
Upvotes: 0
Views: 1519
Reputation: 438467
When you use setSelectedViewController
, the controller has to be one in the tab bar controller's viewControllers
array. But you're creating a new controller here, so it would necessarily fail. You should just use setSelectedIndex
. That's easiest.
So, if you're using NIBs, the didFinishLaunchingWithOptions
might look like:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIViewController *viewController1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
UIViewController *viewController2 = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[viewController1, viewController2];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
// tell the tab bar controller to start with the second tab
[self.tabBarController setSelectedIndex:1];
return YES;
}
If using storyboards, and your initial controller is that tab bar controller, you can:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
[tabController setSelectedIndex:1];
return YES;
}
Upvotes: 3