2009-07-26 15 views
0

我有一個視圖控制器(我們稱之爲MainViewController),它包含一個UITabBarController,其中每個TabBarItem連接到它各自的UIViewController派生類。對於某些UIViewControllers,我想通過MainViewController傳遞值。什麼是做這個代理的最好方法?通過其父級ViewController將值代理到ViewController的最佳實踐?

現在,我最終不得不在MainViewController中爲代理目的創建一個屬性。但理想情況下,我寧願MainViewController不知道它需要傳遞值的特定類型的UIViewController以及它傳遞的特定類型的值,因爲該值從未在MainViewController中使用過,所以我將耦合看作是不必要的。

例如

假設標籤欄項目2連接到UIEmployeeInfoViewController類。而UIEmployeeInfoViewController對稱爲EmployeeInfo類型的對象感興趣。

這是我目前的解決方案,但它是什麼,我試圖避免在尋求更好的辦法做:

 

1) Somewhere where UIMainViewController is being create... 

UIMainViewController *mainViewController = [[UIMainViewController alloc] initWith...]; 

// a property called employeeInfo is created in UIMainViewController class so it can be forwarded later 
mainViewController.employeeInfo = employeeInfoObj; 

... 


2) Code to make UIMainViewController pass the employeeInfo along to UIEmployeeInfoViewController when the tabbar item is tapped: 

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController 
{ 
    if ([viewController class] == [UIEmployeeInfoViewController class]) 
    { 
      // Need to create coupling to UIEmployeeInfoViewController class 
      // and to EmployeeInfo class as well 
      ((UIEmployeeInfoViewController *)viewController).employeeInfo = self.employeeInfo; 
    } 


    return YES; 
} 

回答

0

好了,第一關,不符合人物UI前綴你的類。它保留給UIKit。 Objective-C沒有命名空間,因此使用衆所周知的前綴(特別是Apple使用的前綴)是一個壞主意。

這裏有幾個選項。

您可以創建一個UIViewController子類,使得您的所有類都從其派生,並在創建時採用一些共享控制器對象(如UIMainViewController *),並讓這些類查詢共享對象而不是其他方式。這顛倒了依賴性的本質。

@interface CoreViewController : UIViewController { 
    MainViewController *mainViewController; 
} 

@property (nonatomic, retain, readonly) MainViewController *mainViewController; 

@end 

@implementation CoreViewController 

@synthesize mainViewController; 

- (id) initWithMainViewController:(MainViewController *)mainVC { 
    self = [super initWithNibName:nil bundle:nil]; 

    if (self) { 
    mainViewController = [mainVC retain]; 
    } 

    return self; 
} 

- (void) dealloc { 
    [mainViewController retain]; 

    [super dealloc]; 
} 

@end 

然後通過從self.mainViewController中拉出來獲取數據。根據你的應用程序的性質,這可能是一個非常強大的耦合,另一種選擇是隻是將所有這種共享狀態推到一個單一的對話中。這樣做的好處是,您可以讓所有對象在單例監視器上註冊KVO觀察者以進行更改,而不是顯式檢查它。

+0

感謝您指出使用UI命名空間的使用。不要在我的代碼中使用它,只是使用一個快速的名字。理想情況下,我希望他們根本不瞭解對方,以便他們可以自由插拔和播放。恰巧在這個用例中存在一個依賴關係,但我不希望由此發展任何耦合。也就是說,如果我可以使用MainViewController來了解CoreViewController,反之亦然,那麼我想這樣做。 – Boon 2009-07-26 14:45:27

相關問題