How do I pass data from a tab bar controller to one of its tabs?
If you got an UINavigationController
as one of your UITabBarController
view controllers, you can do the following:
NSArray *viewControllers = [self.tabBarController viewControllers];
UINavigationController *myNavController = (UINavigationController *)viewControllers[2];
MyViewController *myController = [[myNavController childViewControllers] firstObject];
// Remember to alloc/init objects first if the objects haven't been initialized already.
[myController.whateverArray = [[NSArray alloc] initWithArray:@[@"Example1", @"Example2"]];
[self.tabBarController setSelectedIndex:2];
Your best bet is to use notifications.
In your tab bar, you would do this:
NSDictionary *myDictionary; // Populate this with your data.
// Fire the notification along with your NSDictionary object.
[[NSNotificationCenter defaultCenter] postNotificationName:@"Some_Notification_Name"
object:myDictionary];
Then in your child tab ViewController, you would "listen" for that notification.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNotification:)
name:@"Some_Notification_Name"
object:nil];
- (void)handleNotification:(id)object {
// Use your NSDictionary object here.
}
It took a couple of days, but I discovered a simple solution. In my TabBarController's viewDidLoad method, I can access and set attributes of my the tabbed subviews using
[[self viewControllers] objectAtIndex:0]
or whatever index you wish to access.
Saving that as an instance of my tab1_viewController gives me a pointer to the object, from which I can get and set my property values. This was initially unclear because storyboard created the tab_viewController objects for me. I never had a chance to initialize them the way I wanted to!