我有一个每5秒运行一次的功能来检查新消息,如果触发了新消息我正在使用下面的代码更新标签栏项目的徽章值
NSString *chkUrl = @"http://domain.com/script.PHP"; NSURL *url = [[[NSURL alloc] initWithString:chkUrl] autorelease]; NSError *error = nil; NSStringEncoding encoding; NSString *returnHTML = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&encoding error:&error]; int totalNewMessages = [[returnHTML stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] intValue]; AppDelegate *mainDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; NSLog(@"badge before:%@",[[mainDelegate.tabBarController.viewControllers objectAtIndex:2] tabBarItem].badgeValue); [[mainDelegate.tabBarController.viewControllers objectAtIndex:2] tabBarItem].badgeValue = [NSString stringWithFormat:@"%d",totalNewMessages]; NSLog(@"badge after:%@",[[mainDelegate.tabBarController.viewControllers objectAtIndex:2] tabBarItem].badgeValue);
问题是徽章值没有立即更新!也许在第四次通话中它会更新!我做错了什么!或者它是iOS中的错误!
作为一种解决方法,我在每次更新时重复上述行10次,但是它再次没有更新,所以问题是更新徽章值的延迟,这不是重新运行更新行的问题!
顺便说一句,这个问题发生在Xcode 4.6 Simulator&我的iPhone 5与iOS 6.1
解决方法
我发现了问题:)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,(unsigned long)NULL),^(void) { [self checkNewMessages]; });
当我把它改成下面时,它就像一个魅力!
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{ dispatch_async(dispatch_get_main_queue(),^{ [self checkNewMessages]; }); });