可以在后台线程上创建 UIView 吗? [英] Is it ok to create a UIView on a background thread?

查看:25
本文介绍了可以在后台线程上创建 UIView 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 UIView 不是线程安全的,所以我无法在后台线程上添加视图,要解决这个问题,是否可以在后台线程上创建 UIView 然后将其添加到主线程上?

I know UIView are not thread safe so i cant add a view on a background thread, to work around this is it ok to create a UIView on a background thread then add it on the main thread?

注意:我不在主线程上这样做的原因是我的实际代码要复杂得多,因此需要一段时间来创建所有视图并填充值.当我这样做时,我不希望 UI 变得没有响应,所以我试图解决这个问题.

Note: the reason im not doing this on the main thread is because my actual code is a lot more complex and therefor takes a while to create all the views and fill the values. I dont want the UI to become un-responsive when I do this so im trying to work around this.

例如..

-(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:

线程注意事项

对应用程序用户界面的操作必须发生在主线程上.因此,您应该始终从应用程序主线程中运行的代码调用 UIView 类的方法.这可能不是绝对必要的唯一时间是在创建视图对象本身时,但所有其他操作都应在主线程上进行.

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: 的调用可能不是线程安全的,属于操纵"条款.这些当然不能保证是线程安全的.

The call to initWithFrame: is explicitly not thread safe. The call to setText: is likely not thread-safe, falling under the "manipulations" clause. These certainly are not promised to be thread-safe.

努力找出后台线程上的数据.然后在主线程上创建您的视图.如果有大量视图,您可以尝试使用多个 dispatch_async() 调用将工作拆分到主队列上.这可能会让 UI 保持响应;我还没有对它进行过广泛的实验.

Do your work to figure out the data on a background thread. Then create your views on the main thread. If there are a huge number of views, you can try splitting up the work using several dispatch_async() calls onto the main queue. This may let the UI remain responsive; I haven't experimented extensively with it.

您可能还想考虑在可能的情况下从 UIView 切换到 CALayer.大多数CALayer 工作都可以在后台线程上完成.如果您有大量的视图,那无论如何都可能是低效的.如果只是计算视图的数据需要很长时间,则表明您没有正确分离模型和视图信息.模型类应该独立于创建视图计算所需的一切.

You may also want to consider switching from UIView to CALayer where possible. Most CALayer work can be done on background threads. If you have a huge number of views, that's probably inefficient anyway. If it's just that it takes a long time to calculate the data for the views, that suggests you're not properly separating Model and View information. The Model classes should calculate everything needed independently of creating the Views.

这篇关于可以在后台线程上创建 UIView 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆