Is it ok to create a UIView on a background thread?

人走茶凉 提交于 2019-11-27 22:04:45

From 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.

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.

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.

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.

I use Xcode Version 9.0 beta 3 (9M174d), receiving a warning.

[UView init] must be called from main thread only

So I think you should create UI in main thread better

Show the picture below :

The Drawing and Printing Guide states:

Important The UIKit classes are generally not thread safe. All drawing-related operations should be performed on your application’s main thread.

Thus, as I understand this, it seems that the only problem is related to "drawing-related operations". If we assume that a correct class only execute such operation in its drawRect: method, then the approach you suggest should be fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!