Oritm
Oritm

Reputation: 2120

iOS: Call method in tabs viewController

I'm trying to come up with something simple, but i can't figure it out.

I have a UITabBarController and at one point I have to display another tab's UIViewController, and call a method in that new UIViewController, using data from the original UIViewController.

So basically I want to pass data to another UIViewController (that may not be initialized yet), and show the right tab.

If I use NSNotificationCenter, I'm not sure if the tab's UIViewController is initialized yet, and also it's a bit ugly to use delegation here.

What is a clean way to send and show data in the new tab?

Upvotes: 1

Views: 1128

Answers (3)

Abizern
Abizern

Reputation: 150665

A better idea would be to have a protocol implemented in the tab view controller the view controller can call to send data and set up any other view controller

Upvotes: 2

David Wong
David Wong

Reputation: 10294

int x = 1; //this is the view controller you want to go to.
MySecondViewController *secondViewController = (MySecondViewController *)self.tabBarController.viewControllers[x];
[secondViewController setDataObject:dataObject];
[self.tabBarController setSelectedIndex:x];

So what's happening is you're calling the controller from the tabBarController, it will initiate there if its not. Then you can set whatever you want on the controller, then you just switch to the selected tab.

Upvotes: 1

picciano
picciano

Reputation: 22701

You should have a data model of some sort (singleton?) that is accessible by both view controllers. When the second view controller is about to display its view, it should reference the data model to determine the data it should display.

Upvotes: 1

Related Questions