2

I'm trying to figure out programmatically if a particular tab bar item in my app has a badge.

While I'm debugging, visually, I can plainly see that it does. But when I run this code in the viewController in question:

UITabBarItem* thisVCsTabBarItem = self.tabBarItem;
NSString* badgeValue = thisVCsTabBarItem.badgeValue;

...badgeValue is nil. And when I inspect thisVCsTabBarItem in the debugger, its _badgeValue member is nil.

What's going on here? Should I be doing something differently in trying to read this value from the tab bar item?

Thanks.

Greg Maletic
  • 6,225
  • 8
  • 54
  • 73
  • 1
    This should work. Are you sure self.tabBarItem is returning the object you think it is? – Don Feb 26 '10 at 23:25
  • It's a good question. It has the correct title, though the image isn't set...and plainly, it is set, if you look at the tab bar onscreen. So perhaps it's instantiating a new tab bar item, even though one already exists? (I know one already exists, because I'm setting it earlier in the code...that's why I have the badge on it!) – Greg Maletic Feb 27 '10 at 00:00

2 Answers2

2

Looking at some code where I use the UITabBarItem badgeValue property, I see that self.tabBarItem.badgeValue returns nil while self.navigationController.tabBarItem.badgeValue returns the correct value. Could that be it?

The thing is that the auto-completion actually gives me tabBarItem after self. Easy to make a mistake because of that.

Timothée Boucher
  • 1,535
  • 12
  • 30
1

I do something like this for a Downloads tab:

for (UITabBarItem* item in self.tabBarController.tabBar.items) {
    if (item.tag == 3) {
        if (downloadCount > 0) {
            item.badgeValue = [NSString stringWithFormat: @"%d", downloadCount];
        } else {
            item.badgeValue = nil;
        }
    }
}

I don't think you are supposed to access the tabBarItem directly. It is better find your item in the tabBarController's items array.

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
  • Here's what the documentation says: "The default value is a tab bar item that displays the view controller’s title. The first time you access this property, the UITabBarItem is created. Therefore, you shouldn’t access this property if you are not using a tab bar controller." But since I am using a tab bar controller, the implication is that it's no problem for me to access it. Are you aware of something else in the docs that indicates direct access of -[UIViewController tabBarItem] is a problem? Thanks. – Greg Maletic Mar 01 '10 at 02:16