2012-12-27 46 views
1

我有基於TabBar的iPhone應用程序,並且在應用程序委託2中,默認視圖控制器由蘋果初始化(如果您在創建應用程序時選擇了tabbar基本應用程序)。初始化自定義UIViewController

UIViewController *rootViewController = [[tabBarBetFirstViewController alloc] initWithNibName:@"tabBarBetFirstViewController" bundle:nil]; 
UIViewController *accountViewController = [[tabBarBetSecondViewController alloc] initWithNibName:@"tabBarBetSecondViewController" bundle:nil]; 

爲什麼這不是初始化這樣的:

tabBarBetFirstViewController *rootViewController = [[tabBarBetFirstViewController alloc] initWithNibName:@"tabBarBetFirstViewController" bundle:nil]; 
tabBarBetSecondViewController *accountViewController = [[tabBarBetSecondViewController alloc] initWithNibName:@"tabBarBetSecondViewController" bundle:nil]; 

???

這是一樣的嗎?或者這只是由蘋果添加的那些默認設置?如果我想補充一個選項卡將我寫的:

UIViewController *third = [ThirdViewController alloc].....]; 

ThirdViewController *third = [ThirdViewController alloc]....]; 

當然在最後我有:

self.tabBarController = [[UITabBarController alloc] init]; 
self.tabBarController.viewControllers = [NSArray arrayWithObjects:rootViewController, accountViewController, third, nil]; 
+0

只是要注意,我用的是蘋果的版本,UIViewController中*第三= [ThirdViewController頁頭] ...];和它的工作......但只是想知道什麼是正確的做法。 – user1832330

回答

0

您使用

ThirdViewController *third = [ThirdViewController alloc]....]; 

方法。不知道爲什麼蘋果使用其他方法。我這個簡單的例子,它沒有任何區別。但是當你想要設置屬性時,最好使用類名。

0

這取決於,如果你有一個視圖控制器,你想有一個自定義接口,你會希望它是UIViewController的子類。如果ThirdViewController是UIViewController的子類,那麼您在此處陳述的代碼如下:

ThirdViewController *third = [ThirdViewController alloc]....]; 

會產生期望的結果。 Apple的方法僅適用於沒有任何屬性的通用View Controller,因此理想情況下您希望所有選項卡都是UIViewController的子類。

2

ThirdViewControllerUIViewController的一個子類,所以你可以寫兩者。但是,如果你以後想使用變量third調用特定於ThirdViewController方法,那麼你應該使用

ThirdViewController *third = [ThirdViewController alloc]....]; 

總結起來:在這個簡單的場景出現的「做」沒有唯一正確的途徑。從這個問題中得出的重要教訓(如果它不是很清楚)是瞭解爲什麼您可以將一個ThirdViewController實例分配給一個UIViewController變量(因爲子類化關係)。

+0

哦,這是有道理的:D。好吧,我只是在應用程序委託中使用它(就像我寫的),所以在這種情況下不要調用任何方法,只需將它們添加到tabbarcontroller ... thx – user1832330

0

1)如果你想利用你的ThirdViewController任何實例方法或屬性,則必須使用

ThirdViewController *third = [ThirdViewController alloc]....]; 

2)如果你沒有必要這麼做,你可以使用

UIViewController *third = [ThirdViewController alloc]....]; // it'd make no difference 

爲了更安全一方,imo,第一種情況是一種很好的做法。

0

在這種情況下,我沒有看到任何區別,我寧願按照自己的方式做。但在類似下面的一個情況下,蘋果公司的方式似乎更好:

UIViewController *vc; 

if (some_case){ 

    vc = [YourViewController1 alloc]// ...; 
    [ (YourViewController1 *) vc doSomeThing]; // You might need to use casting for instance messages 
    //... 
} 

else { 

    vc = [YourViewController2 alloc]//...; 
} 

[self.navigationController pushViewController:vc animated:YES]; 
[vc release];