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

查看:492
本文介绍了可以在后台线程上创建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


线程注意事项

Threading Considerations

操作您的应用程序的用户界面必须出现在主线程上。因此,您应该始终从应用程序主线程中运行的代码调用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 工作可以在后台线程上完成。如果您有大量的观点,那么无论如何都可能效率低下。如果仅仅需要花费很长时间来计算视图的数据,则表明您没有正确地分离模型和视图信息。 Model类应该独立于创建视图来计算所需的一切。

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天全站免登陆