我已经搜索了很多,但无法找到答案,因此决定问你:)。
我有一个带有一些视图的应用程序。登录后,我创建了一个UITabBarController与3选项卡。
现在我希望根据用户有多少通知来更改第二个选项卡的徽章。
这个核心在viewdidload方法中调用时工作:
NSString *badgeValue = [NSString stringWithFormat:@"%i", [cacheNotifications count]];
if([cacheNotifications count] != 0){
[[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:badgeValue];
}
但是,我在后台运行了一个守护进程,每30秒检查一次通知。如果我能改变这个守护进程的徽章就太好了。
当我调用像这样的东西时:
PlatformViewController *theInstance = [[PlatformViewController alloc] init];
[theInstance updateNotificationsBadge];
调用函数,但不更新徽章。有或没有performSelectorOnMainThread.
updateNotificationsBadge:
-(void) updateNotificationsBadge{
NSString *badgeValue = [NSString stringWithFormat:@"%i", [cacheNotifications count]];
NSLog(@"Length here is: %i", [cacheNotifications count]);
if([cacheNotifications count] > 0){
NSLog(@"call..");
[self performSelectorOnMainThread:@selector(setNotification:)
withObject:badgeValue
waitUntilDone:YES];
}
}
-(void)setNotification:(NSString*)badge{
NSLog(@"Called. %@", badge);
[[[[[self tabBarController] viewControllers] objectAtIndex: 1] tabBarItem] setBadgeValue:badge];
}
我该如何解决这个问题?
提前感谢!
编辑:cachenotification是在globalVars.m中声明的全局变量。当我调用一个新实例时,它不会被重新初始化。
我从daemonClass.m
调用下面的代码PlatformViewController *theInstance = [[PlatformViewController alloc] init];
[theInstance updateNotificationsBadge];
您需要使用现有的引用,而不是为platformViewController
创建一个新的实例。当您创建一个新的数组时,cacheNotification
数组将不是initialized
,也没有contents
在其中。所以总是返回0
和UITabBarController
是一个containerViewController
包含了所有的viewControllers
。因此,您不需要从其他类更改选项卡badgeValue
。
和在setNotification:
方法中,像这样更改badgeValue
。
[[[[self tabBarController] tabBar] items] objectAtIndex:1] setBadgeValue:badge];
您应该使用相同的类实例,而不是创建一个新的。这会破坏之前的值。当你获得一个徽章时,我建议使用NSNotificationCenter来发布通知,它将在platformViewController
类中实现徽章的void getter和setter方法。这样就不会销毁任何实例。
希望能有所帮助
我真的不知道你的问题,但我认为我会使用nsobject的子类,并在每个viewController我会改变徽章。类似如下:https://stackoverflow.com/a/9736559/2000162
func setBadge(){
let viewconrollers = self.tabBarController?.viewControllers
viewconrollers![3].tabBarItem.badgeValue = "Your String value"
viewconrollers![3].tabBarItem.badgeColor = UIColor.green
}
//call setBadge() method from view controller's viewdidload method.
// select your give number it the view controllers array for providing badge on the desired tab