views:

405

answers:

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.

A: 

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.

St3fan
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
A: 

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