我有一个视图控制器,可以加载一个自定义视图(然后绘制UI元素,然后生成一个线程来在后台做一些事情。
如果“在后台运行的东西”遇到错误,我的视图控制器会捕获它,此时我想更改UI元素,比如bgcolor或添加新标签。
但我所做的任何改变都没有出现。这就是我正在尝试的:
[self performSelectorOnMainThread:@selector(onCompleteFail) withObject:nil waitUntilDone:YES];
- (void)onCompleteFail
{
NSLog(@"Error: Device Init Failed");
mLiveViewerView.backgroundColor= [UIColor whiteColor];
//self.view.backgroundColor = [UIColor whiteColor];
UILabel *tmpLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 200, 30)];
tmpLabel.text = @"Failed to init";
[self.view addSubview:tmpLabel];
}
答案 0 :(得分:1)
你需要在主线程上进行任何与UI相关的调用:UIKit不是线程安全的,你会看到各种奇怪的行为,就好像它是一样。这可能就像从
切换一样简单[self onCompleteFail];
到
[self performSelectorOnMainThread:@selector(onCompleteFail) withObject:nil waitUntilDone:NO];
...或者如果由于其他原因必须在后台线程上调用-onCompleteFail
,您可以将UI调用包装到主队列中,如下所示:
- (void)onCompleteFail
{
NSLog(@"Error: Device Init Failed");
dispatch_async(dispatch_get_main_queue(), ^{
mLiveViewerView.backgroundColor= [UIColor whiteColor];
//self.view.backgroundColor = [UIColor whiteColor];
UILabel *tmpLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 200, 30)];
tmpLabel.text = @"Failed to init";
[self.view addSubview:tmpLabel];
});
}