我知道UIView不是线程安全所以我不能在后台线程上添加一个视图,要解决这个问题,可以在后台线程上创建一个UIView然后将其添加到主线程上吗?
注意:我不在主线程上执行此操作的原因是因为我的实际代码要复杂得多,因此需要一段时间来创建所有视图并填充值.当我这样做时,我不希望UI变得无响应,所以我试图解决这个问题.
例如..
-(void)addLabel//called on background thread
{
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0,0,40,100)];
[label setText:@"example"]
[self.view performSelector:@selector(addSubview:) onThread:[NSThread mainThread] withObject:example waitUntilDone:YES];
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
我是Objective C的新手,来自.NET和java背景.
所以我需要异步创建一些UIwebviews,我在自己的队列中使用
dispatch_queue_t queue = dispatch_queue_create("myqueue", NULL);
dispatch_async(queue, ^{
// create UIwebview, other things too
[self.view addSubview:webView];
});
Run Code Online (Sandbox Code Playgroud)
正如你所想象的那样会抛出一个错误:
bool _WebTryThreadLock(bool), 0xa1b8d70: Tried to obtain the web lock from a thread other
than the main thread or the web thread. This may be a result of calling to UIKit from a
secondary thread. Crashing now...
Run Code Online (Sandbox Code Playgroud)
那么如何在主线程上添加子视图呢?