我已经阅读了所有我能找到的相关问题,但仍然卡住了,所以我希望有人能够发现我的推理错误。即使更新从主线程调用,UI也不会更新
我想定期更新一些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”?一个浮点数我想.. – 2012-03-02 15:26:31
你试过用NSTimer吗?也许在viewDidLoad中,你启动了一个NSTimer。打勾时,让它执行你的UI更新。在单个视图中使用2个独立的自引用过程有点令人困惑。 – Jeremy 2012-03-02 15:27:12
@RaphaelAyres是的。 – Tom 2012-03-02 15:40:11