我有一个最奇怪的事情,我有一个uinavigationgroup,并且所有页面都是从custenViewController继承的,控制器在右上方添加了一个带有红色徽章的按钮,其中包含一个迭代器。该应用程序可以具有无限页面,因此所有页面都从此处扩展。所以我可以一次更改所有页面上的迭代器,每个页面都有setBadge函数。
#import "CustomView.h"
@interface CustomView ()
@end
@implementation CustomView
- (void)viewDidLoad
{
[super viewDidLoad];
// add notification icon
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icn_notification.png"]
style:UIBarButtonItemStylePlain
target:self
action:@selector(openNotifications:)];
self.navigationItem.rightBarButtonItem = rightButton;
// add the badge and set it hidden
badge = [[UILabel alloc] init];
badge.frame = CGRectMake(270, -45, ( ( 1 * 8 ) + 14), 22);
badge.hidden = false;
badge.text = @"?";
badge.textColor = [UIColor whiteColor];
badge.backgroundColor = [UIColor redColor];
badge.layer.cornerRadius = 11;
badge.textAlignment = NSTextAlignmentCenter;
badge.font = [UIFont systemFontOfSize:16];
badge.shadowColor = [UIColor clearColor];
badge.shadowOffset = CGSizeMake(0,0);
self.navigationController.navigationBar.layer.zPosition = -1;
[self.view addSubview:badge];
// set the count to the badge
appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.myData addCustomView:self];
[self setBadge: appDelegate.myData.badgeCount];
}
-(void)setBadge: (int)count{
// set the number
NSString *text = [[NSString alloc] initWithFormat:@"%d", count];
[badge setText:text];
[badge setFrame:CGRectMake(270, -45, ( ( [text length] * 8 ) + 14), 22)];
[badge setHidden: (count == 0)];
}
-(void)openNotifications: (id)sender
{
// open the subview
[self.navigationController pushViewController:appDelegate.notificationView animated:YES];
}
@end
当我更新所有徽章时,我会这样做:
// update badges
for (CustomView *view in customViews) {
[view setBadge: self.badgeCount];
}
这确实有效,只有最奇怪的事情是不会马上做,有时会有1分钟的延迟,当我在应用程序中更改页面看起来它变得更快,但我真的不明白延迟! / p>
有人请帮忙!这花了太长时间!
谢谢!
好的感谢David H,我在主线程上执行它,只有当我不在主线程上时会发生什么?代码没有被执行所以我应该做什么呢?
// UI stuff make sure im on the Main Thread
if( [NSThread isMainThread] ){
// update badges
for (CustomView *view in customViews) {
[view setBadge: self.badgeCount];
}
// refresh table
[self.nTable reloadData];
[self.mTable reloadData];
}else{
NSLog(@"NOT ON MAIN!!!! %d", [NSThread isMainThread]);
}
这很有效,只有这个创造了我的代码没有执行的理论情况.....现在我不知所措
答案 0 :(得分:0)
在你的“for循环”中,在它开始之前,确保你在主线程上:assert([NSThread isMainThread]);,如果不是会发生各种奇怪的事情。我在我的代码中使用这些断言来确保UI活动永远不会发生在任何其他线程上。这些问题可能需要数周才能追踪,但如果您使用大量的块并调度队列(就像我一样),通常会突然出现。
要处理在其他线程上接收它,只需将整个内容包装在一个调度块中,然后将其发送到主线程。你真的不需要检查你是如何得到的,代码将始终有效,因为它在主线程上。