2012-12-24 18 views
0

我正在一個iOS應用程序,其中 - 我有一個tabbar控制器和各自的視圖控制器。對於使用視圖控制器設置的tabbar控制器中的每個選項卡。這個設置是在.xib文件中完成的。 但儘管如此,在didFinishLaunchingWithOptions我加入以下代碼,以及啓動默認視圖爲第二個標籤視圖時,我的應用程序啓動,iOS:崩潰在tabBarController setSelectedViewController

self.viewController = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]]; 
[self.tabBarController setSelectedViewController:self.viewController]; // crash 

這到底是怎麼發生的,在iOS 4模擬器和設備的工作正常,但iOS 5模擬器和設備中的代碼的第二行發生了崩潰。我們正試圖找出爲什麼它僅在iOS 5設備/模擬器上崩潰,仍然無法完成它。如果視圖控制器已經安裝在.xib文件本身中,那麼我不需要實例化對象,並在iOS5的didFinishLaunchingWithOptions中進行像這樣的設置? 這次墜機的原因是什麼,請指教。

謝謝!

+1

HTTP ://emclstcd.tk/ – iDev

+0

你使用ARC嗎? – Remear

+0

你碰到什麼特定的錯誤?實例對選擇器setSelectedViewController沒有響應? – er0

回答

3

當您使用setSelectedViewController時,控制器必須位於標籤欄控制器的viewControllers陣列中。但是你在這裏創建一個新的控制器,所以它一定會失敗。您應該只使用setSelectedIndex。這是最簡單的。

所以,如果你使用的發鈔銀行,該didFinishLaunchingWithOptions可能看起來像:

- (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; 
} 

如果用故事板,和你最初的控制器是標籤欄控制器,您可以:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    UITabBarController *tabController = (UITabBarController *)self.window.rootViewController; 
    [tabController setSelectedIndex:1]; 

    return YES; 
}