[英]Identify UITabBarItems view controller instances the proper way
我有一個帶有標簽欄的應用程序來打開不同的視圖控制器,如下所示:
firstViewController = [[UITableViewController alloc] init];
UINavigationController *firstNavigationController = [[UINavigationController alloc] initWithRootViewController:firstViewController];
[firstNavigationController setTabBarItem:[[UITabBarItem alloc] initWithTitle:@"Add" image:[UIImage imageNamed:@"Add.png"] tag:1]];
[viewControllers addObject:firstNavigationController];
secondViewController = [[UITableViewController alloc] init];
UINavigationController *secondNavigationController = [[UINavigationController alloc] initWithRootViewController:secondViewController];
[secondNavigationController setTabBarItem:[[UITabBarItem alloc] initWithTitle:@"List" image:[UIImage imageNamed:@"List.png"] tag:2]];
[viewControllers addObject:secondNavigationController];
UITabBarController *tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:viewControllers];
[[self window] setRootViewController:tabBarController];
這可以。 現在,我還有一個附加的導航要求,可以從secondViewController調用firstViewController,將數據傳遞給它。
我發現將數據傳遞到選項卡欄訪問的firstViewController的相同實例的唯一方法是以下方式(在secondViewController代碼中):
firstViewController = [[[[[self tabBarController] viewControllers] objectAtIndex:0] viewControllers] objectAtIndex:0];
這可以很好地工作 ,但是我感到混亂,特別是如果我決定更改標簽欄控制器中視圖的順序時。
我也探索了標記方式,但是似乎並沒有對代碼進行太多改進。
還有另外一種更清潔的方法嗎?
我不能聲稱知道您要通過從一個視圖控制器向另一個視圖控制器發送數據來完成什么工作,但是如果發送數據是您的唯一目的,那么我建議您使用Singleton模式 。 或者我會推薦NSNotificationCenter 。 單例可以容納可從任何地方檢索的應用程序范圍的數據。 您甚至可以(盡管它違反了最佳實踐)在單例類中保留對您的視圖控制器的引用。 我還大量使用通知來傳遞數據。 只需發布通知,然后讓另一個班級收聽它。
例如,在viewDidLoad中的firstViewController中,您可以執行以下操作:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(theMethodToCall:) name:@"myNotificationName" object:nil];
然后在secondViewController中,當您想傳遞數據時,可以發布以下內容(其中“ myData”是數據對象(如NSDictionary)):
[[NSNotificationCenter defaultCenter] postNotificationName:myNotificationName object:nil userInfo: myData];
然后在firstViewController中,此方法將接收數據。
-(void)theMethodToCall:(NSNotification *)notif
{
NSDictionary *dict = [notification userInfo];
}
通過此代碼,您還可以獲得不錯的對象參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.