Trying to pass data between tab bar controllers

471 views Asked by At

I'm trying to pass some data between my views in a tab bar. my first view is able to load the data from my model class and manipulate it. But when I hit the second or third tab in my tab bar controller, the data doesn't get passed. Here's how I'm attempting to pass it.

-(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 is the name of the instance of my model class I created in the current view controller. I'm trying to avoid making multiple instances of the model class since it has to make multiple calls to an API. All I'm trying to do is pass the feed.userArray to the different views to be manipulated differently.

2

There are 2 answers

1
Ram Suthar On

Do not create view controllers in this method. UITabBarController automatically creates all view controllers on initialisation. Try this instead:

-(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;
    }
}
2
V.J. On

You are creating new ViewController instance. Instead of this you need to get the selected viewcontroller from the TabBarController's ViewController array. I have changed your code. So check it below.

NOTE:

Please solve the Spelling mistake/Method names. Because i have write this in the notepad. Not in 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;
    }       
}