pouncelciot
pouncelciot

Reputation: 51

Can not pass data when adding navigation controller to view

I have a TabBarController with three tabs. The views for all tabs were embedded in their own navigation controller, except one, the Map view. To navigate from one of the other views to the Map view and pass data I used:

- (IBAction)mapButton:(id)sender {
    MapViewController *destView = (MapViewController *)[self.tabBarController.viewControllers objectAtIndex:0];
    if ([destView isKindOfClass:[MapViewController class]])
    {
        MapViewController *destinationViewController = (MapViewController *)destView;
        destinationViewController.selectedTruck = _truck;
    }
    [self.tabBarController setSelectedIndex:0];
}

And it was working. Now I need to embed the Map view in a navigation controller as well, to add a detail view, but when I do no data is passed, it only goes to the Map view.

Can anyone see what am I missing?

Upvotes: 0

Views: 46

Answers (1)

johnpatrickmorgan
johnpatrickmorgan

Reputation: 2372

[self.tabBarController.viewControllers objectAtIndex:0] is no longer an instance of MapViewController. It is a UINavigationController with a MapViewController as its root view controller.

You could access the MapViewController via the UINavigationController like so but all these type casting assumptions are messy -

- (IBAction)mapButton:(id)sender {
    UINavigationController *navigationController = (UINavigationController *)[self.tabBarController.viewControllers firstObject];
    if ([navigationController isKindOfClass:[UINavigationController class]])
    {
        MapViewController *rootViewController = (MapViewController *)[navigationController.viewControllers firstObject];
        if ([rootViewController isKindOfClass:[MapViewController class]])
        {
            MapViewController *destinationViewController = (MapViewController *)rootViewController;
            destinationViewController.selectedTruck = _truck;
        }
    }
    [self.tabBarController setSelectedIndex:0];
}

Instead, a better design would be to keep a reference to the MapViewController (as a property) when you set up the tab bar. That way you would simply call self.destinationViewController.selectedTruck = _truck; instead.

Upvotes: 1

Related Questions