2013-07-02 41 views
0

我有三個ViewControllers:更新UITableView的數據

RootViewController 
FirstViewController 
SecondViewController 

從創建與其他兩個ViewControllers一個TabBarController的RootViewController的。所以我需要這樣做:

FirstViewController *viewController1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil]; 

SecondViewController *viewController2 = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; 

然後將控制器添加到TabBarController。 在那一刻,我的兩個ViewController被實例化。

要更新我在FirstViewController.m嘗試這樣的數據:

SecondViewController *test = [[SecondViewController alloc] init]; 
[test.tableView reloadData]; 

但什麼也沒有發生,我想是因爲我SecondViewController之前已被分配,並且正在創建它的一個新的實例。

如何從我的FirstViewController更新SecondViewController中的Table的數據?

回答

1

讓您的根視圖控制器在創建它們時將viewController2的值傳遞給viewController1。描述屬性很弱,因爲你想讓rootController擁有它們,而不是其他viewController。

0

您的TabBarController是否持有FirstViewControllerSecondViewController?在TabBarController,有一個屬性 - viewControllers。它是一個數組,所以你可以使用它來訪問你的viewControllers。

[tabBarController.viewControllers objectAtIndex:0];//This is your First viewController 
[tabBarController.viewControllers objectAtIndex:1];//This is your Second viewController 

然後訪問sencondViewController的tableView並重新加載它。

希望這是有幫助的。

1

如果您嘗試更新第二個視圖控制器中使用的數據而不需要切換,我將使用委託模式。

創建FirstViewController協議的聲明像

@class FirstViewController; 

@protocol FirstViewControllerDelegate 

-(void) updateDataFromFirstViewController: (NSMutableArray*)newArray; 

@end 

@property (strong, nonatomic) id<FirstViewControllerDelegate>delegate; 

然後當你有新的數據來更新呼叫

[self.delegate updateDataFromFirstViewController:yourNewData]; 

實現SecondViewController.m這種方法,並委託添加到您的firstViewController SecondView Controller.h

SecondViewController: UIViewController <FirstViewControllerDelegate> 

Th在

-(void) viewWillAppear:(BOOL)animated 

重新加載您的表數據,以便當您實際需要查看更新的數據時,它在切換時出現。另外,不要忘記在SecondViewController中將FirstViewController委託設置爲self。

+0

我當tryn到添加到SecondViewController.h錯誤(它說,委託不存在):S –

+0

沒有你'#進口「FirstViewController。h「' –

-1

這會幫助你。您可以通過這種方式訪問​​secondViewController。

UITabBarController *tabController = (UITabBarController *)[self parentViewController]; 

[tabController.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 

    if ([obj isKindOfClass:[SecondViewController class]]) { 
     SecondViewController *secondController = obj; 
     [secondController.tableView reloadData]; 
     *stop = YES; 

    } 

}]; 
+0

正如orange9792所建議的那樣,在這種情況下委託人會更合適,我會盡可能避免在層次結構上列舉。 –