2015-06-25 51 views
4

我試圖在標籤欄中的視圖之間傳遞一些數據。我的第一個觀點是能夠從我的模型類中加載數據並對其進行處理。但是當我點擊標籤欄控制器中的第二個或第三個標籤時,數據不會通過。以下是我試圖通過它的方式。試圖在標籤欄控制器之間傳遞數據

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{ 

if (tabBarController.selectedIndex == 1){ 
HashTagTableViewController *hash [[HashTagTableViewController alloc]init]; 
    hash.userArray = feed.userArray; 
}else if (tabBarController.selectedIndex == 2){ 
    PhotoTagTableViewController *photo = [[PhotoTagTableViewController alloc]init; 
    photo.userArray = feed.userArray; 

} 

} 

feed是我在當前視圖控制器中創建的模型類實例的名稱。我試圖避免創建模型類的多個實例,因爲它必須對API進行多次調用。我所要做的就是將feed.userArray傳遞給不同的視圖以進行不同的操作。

+0

因此'feed'是您的模型數據。您正在做正確的事情並正確使用MVC模式。現在您需要設置一些斷點,並在設置階段以及從視圖控制器的角度檢查數據的外觀。 – Droppy

+0

在這個階段,hash.userArray設置得很好。但是當它切換到HashTagTableViewController時,hash.userArray變爲空。 –

回答

3

請勿在此方法中創建視圖控制器。 UITabBarController在初始化時自動創建所有視圖控制器。試試這個:

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{ 
    if (tabBarController.selectedIndex == 1){ 
     HashTagTableViewController *hash = (HashTagTableViewController *) viewController; 
     hash.userArray = feed.userArray; 
    }else if (tabBarController.selectedIndex == 2){ 
     PhotoTagTableViewController *photo = (PhotoTagTableViewController *)viewController; 
     photo.userArray = feed.userArray; 
    } 
} 
+0

崩潰,並得到這個錯誤:[UINavigationController setUserArray:]:無法識別的選擇發送到實例0x7fc5fb4cf880 –

0

您正在創建新的ViewController實例。取而代之,你需要從TabBarController的ViewController數組中獲取選定的視圖控制器。我改變了你的代碼。所以在下面檢查。

注:

請解決拼寫錯誤/方法名。因爲我在記事本中寫了這個。不在xcode中。

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController 
{ 
    if([viewController isKindOfClass: [HashTagTableViewController class]]) 
    { 
     HashTagTableViewController *hash = (HashTagTableViewController) viewController; 
     hash.userArray = feed.userArray; 
    } 
    else if([viewController isKindOfClass: [PhotoTagTableViewController class]]) 
    { 
     PhotoTagTableViewController *photo = (PhotoTagTableViewController) viewController; 
     photo.userArray = feed.userArray; 
    }  
} 
+0

是不是'vc'已經傳入'viewController'? – Droppy

+0

是的。它在viewController中傳遞。你是對的@Droppy –

+0

這是我第一次嘗試。使用調試器,它會跳過第一個if語句,因爲viewController類是UINaviagtionController類。 –

相關問題