views:

332

answers:

3

I have a tabBar with 4 tabs on it, and I want to perform some action when a specific tab is selected, so I have uncommented the UITabBarControllerDelegate in the xxAppDelegate.m

I also wanted to see the value that was being sent logged in the console - in order to test my "if" statement. However this is where I got stumped.

// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

    NSLog(@"%@", viewController);
}

The console dutifully logged any selected controller that had been selected, but in this particular format:

<MyViewController: 0x3b12950>

Now, I wasn't expecting the square brackets or the colon or the Hex. So my question is how do I format my IF statement? This is what I thought would work but I get an error mentioned further down.

// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

    NSLog(@"%@", viewController);
    if (viewController == MyViewController)
    {
    //do something nice here …
    };
}

... The error is "Expected expression before 'MyViewController'"

Anyone know how I should be doing this?

+1  A: 

You need to compare to a specific view controller instance. For example, if the if statement should be true when the second tab is selected:

if (viewController == [tabBarController.viewControllers objectAtIndex:1]) {
    // ...
}
Ole Begemann
A: 

Thanks that worked. I guess you have to know what object your comparing against first.

For anyone reading this the code supplied works, however you need to be careful that the text "tabBarController" in the example refers to the instance variable (the global one).

In order for your code to work your view controller needs to refer to a uniquely named local version as follows. Compare this to my original code.

// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController_local didSelectViewController:(UIViewController *)viewController 
{
//...
}

Hope this helps someone faced with the

Local declaration of 'tabBarController' hides instance variable 

warning when trying to implement.

T9b
A: 

When comparing tabbarcontroller use self. like this.

if (viewController == [self.tabBarController.viewControllers objectAtIndex:1]) { // ... }

it will remove the warning.... :-)

Faiz