Question

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.

Was it helpful?

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";

OTHER TIPS

Assuming your ViewControllers are loaded from a StoryBoard, call your function to update the tabBarItem badgeValue in 'initWithCoder:' of the ViewController whose tabBarItem badgeValue you want to update. The ViewControllers that are associated with tabs in the TabBarController are initialized when the TabBar loads.

The code could look something like this:

    - (id) initWithCoder:(NSCoder *)aDecoder
    {    
          self = [super initWithCoder:aDecoder];

          NSString* badgeValue = [self calculateBadgeValue];  //your method
          self.tabBarItem.badgeValue = badgeValue;

          return self;
     }

If you do this, the badge should update when the TabBar becomes visible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top