【发布时间】:2012-03-02 15:18:11
【问题描述】:
我已经阅读了我能找到的所有相关问题,但我仍然卡住了,所以我希望有人能发现我的推理错误。
我正在尝试定期更新一些 UIView。为简单起见,我将代码简化为以下内容。摘要:在 viewDidLoad 中,我在一个新的后台线程上调用了一个方法。该方法调用主线程上的一个方法,该方法应该更新一些 UILabel。代码似乎工作正常:后台线程不是主线程,调用 UILabel 更新的方法在主线程上。在代码中:
在 viewDidLoad 中:
[self performSelectorInBackground:@selector(updateMeters) withObject:self];
这会创建一个新的后台线程。我的方法 updateMeters(为简单起见)现在看起来像这样:
if ([NSThread isMainThread]) { //this evaluates to FALSE, as it's supposed to
NSLog(@"Running on main, that's wrong!");
}
while (i < 10) {
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
//The code below yields the same result
// dispatch_async(dispatch_get_main_queue(), ^{
// [self updateUI];
// });
[NSThread sleepForTimeInterval: 1.05];
++i;
}
最后,updateUI 就是这样做的:
if ([NSThread isMainThread]) { //Evaluates to TRUE; it's indeed on the main thread!
NSLog(@"main thread!");
} else {
NSLog(@"not main thread!");
}
NSLog(@"%f", someTimeDependentValue); //logs the value I want to update to the screen
label.text = [NSString stringWithFormat:@"%f", someTimeDependentValue]; //does not update
据我所知,这应该可行。但不幸的是,它没有......注释掉的dispatch_async() 产生相同的结果。
【问题讨论】:
-
什么是“someTimeDependentValue”?我想是一个浮点数..
-
你试过使用 NSTimer 吗?也许在 viewDidLoad 中,你启动了一个 NSTimer。在勾选时,让它执行您的 UI 更新。在单个视图中使用 2 个独立的自引用进程有点令人困惑。
-
@Jeremy 你的意思是这样的吗?
[self performSelectorInBackground:@selector(updateMeters) withObject:self];NSInvocation *invoc = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(updateUI)]];[NSTimer timerWithTimeInterval:1. invocation:invoc repeats:YES];我不熟悉 NSInvocation 对象,所以我不确定这是正确的。使用此代码,不会调用 updateUI。 -
我没有得到它应该更新的内容,这就是价值。你有没有想过可能 someTimeDependentValue 没有被评估?使用 NSlog 或断点检查它是否确实有一些值。
-
@Andrea 对不起。为了简洁起见,我删除了一个 NSLog() 语句。 someTimeDependentValue 确实得到了更新。
标签: objective-c ios nsthread performselector