Search code examples
iosuiviewcontrollertransfer

New ways to transfer data between view controllers


I have a problem with transferring data between UIViewController and I don't find answers in former questions.

Situation : I have a first viewController ('CalViewController') which allows users to input data. Then I calculate with those datas a number (named 'calories' for example). The next views are two UIViewController (DrinksViewController & FoodViewController)displayed in a TabBarControllerand I need value of 'calories'.

What I've tried : -prepareForSegue method : It doesn't work because segues (symbol in storyboard is a link between two points) in a TabBarControllerare not as others (symbol in storyboard is arrow through a door).

-'didSelectViewController' method : This method is not "activated" to display the first view of a TabBarController. So I succeed to transfer Calories to my second ViewController in the TabBarController (ie FoodViewController) but not to my first viewController in the TabBarController (ie DrinksViewController).

-call the "original" value : Here what I've done in CalViewController (after imported DrinksViewController.h)

DrinksViewController *dvc = [[DrinksViewController alloc] init]; 
dvc.caloriesImported = 456;

I don't know why this third way is not working.

Problem : My value of Caloriesis not transferred from CalViewController to DrinksViewControlller. Any ideas ?


Solution

  • If I understand your problem correctly, the following should work in the first view controller CalViewController:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([[segue identifier] isEqualToString:@"yourSegueToTabBarIdentifier"]) {
            UITabBarController *tbc = [segue destinationViewController];
            DrinksViewController *dvc = tbc.viewControllers[0];
            dvc.caloriesImported = 456;
            FoodViewController *fvc = tbc.viewControllers[1];
            fvc.someProperty = someValue;
        }
    }
    

    Note that

    DrinksViewController *dvc = [[DrinksViewController alloc] init]; 
    dvc.caloriesImported = 456;
    

    cannot work because it allocates a new instance of DrinksViewController that is completely unrelated to the instance used by the tab bar controller.