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