Search code examples
iostabbarappdelegatebadge

Reload badge of tab bar item


I have an app with a tab bar controller. One of these views is a table view. There is a method to set the badge of this view in the tab bar. This works...but only when the user touches this view and not right on launching the app. So I tried to use this method in appDelegate...but this doesn`t work. my method in the view:

    @property (strong) NSMutableArray *cars;
//some code here

    -(void)SelectBadge
    {
        int r = [_cars count];
        if (r == 0) {
            self.navigationController.tabBarItem.badgeValue = 0;
        }
        else {
        self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", r];
        }
        [self.tableView reloadData];
    }

I tried to put this method in my appDelegate file:

- (void)applicationDidBecomeActive:(UIApplication *)application
{    
    CarList *Instance = [[CarList alloc] init];
    [Instance SelectBadge];
}

Thanks to all your answers beforehand.


Solution

  • The way I see it is you are creating a new intance of CarList in this - (void)applicationDidBecomeActive:(UIApplication *)application method. So In selectBadge function the self.navigationController.tabBarItem.badgeValue = someValue; will be setting badge value for some other instance.

    Try addressing the correct instance. If you can access the UITabBarController instance then you can do this:

    UITabBar     *tabBar = mTabBarController.tabBar;
    UITabBarItem *someItem  = [tabBar.items objectAtIndex:0];////You can put your interested tabBarItem index
    someItem. badgeValue = @"100";