objective-c – 在后台线程上创建UIView可以吗?

栏目: Objective-C · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/11122957/is-it-ok-to-create-a-uiview-on-a-background-thread

我知道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];
}

提前致谢.

UIView

Threading Considerations
Manipulations to your application’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself but all other manipulations should occur on the main thread.

对initWithFrame的调用显然不是线程安全的.对setText的调用可能不是线程安全的,落在“操纵”子句下.这些肯定不会是线程安全的.

做你的工作,找出背景线上的数据.然后在主线程上创建您的视图.如果有大量的视图,您可以尝试使用几个dispatch_async()调用分割到主队列上.这可能让UI保持响应;我没有广泛地尝试过.

您也可以考虑在可能的情况下从UIView切换到CALayer.大多数CALayer工作可以在后台线程上完成.如果你有很多观点,那可能是低效的.如果只是计算视图的数据需要很长时间,这表明您没有正确分离模型和视图信息. Model类应该独立于创建视图来计算所需的所有内容.

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/11122957/is-it-ok-to-create-a-uiview-on-a-background-thread


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Code Complete

Code Complete

Steve McConnell / Microsoft Press / 2004-6-19 / GBP 40.99

在线阅读本书 Widely considered one of the best practical guides to programming, Steve McConnells original CODE COMPLETE has been helping developers write better software for more than a decade. Now......一起来看看 《Code Complete》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具