问题
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 TabBarController
and 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 TabBarController
are 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 Calories
is not transferred from CalViewController
to DrinksViewControlller
. Any ideas ?
回答1:
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.
回答2:
You need to get the instances that are already in the tab bar controller. You do that with self.tabBarController.viewControllers[n], where n would be 0,1, or 2 depending on which controller you're trying to access.
来源:https://stackoverflow.com/questions/18165514/new-ways-to-transfer-data-between-view-controllers