dispatch_async 初始化 UIView 对象时

dispatch_async when initializing UIView objects

问题来了:

我有一些包含许多子视图的重视图,我需要加载然后显示它们。我想异步执行它,这样我就不会阻塞我的主线程。当我尝试异步执行时,我遇到了以下困境:

完成所有繁重的工作后,我 return 进入主队列以实际显示这些内容,但我遇到了问题。首先,即使一切都已完成,所有视图都需要 30-60 秒才能显示出来。有时他们会放错地方。我可能做错了什么,我应该寻找什么?

private func loadScrollViews() {
    let qos = Int(QOS_CLASS_USER_INTERACTIVE.value)
    dispatch_async(dispatch_get_global_queue(qos, 0)) { () -> Void in
        // Creating many UIViews
        for var i = 0; i < 100; i++ {
            let view = UIView(frame: someFrame)
            self.viewCollection.append(view)
        }
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.displayViews()
        })
    }
}

private func displayViews() {
    for view in self.viewCollection {
        self.contentView.addSubview(view)
    }
    self.activityIndicator.stopAnimating()
    self.contentView.hidden = false
}

像我说的那样执行 displayViews 后,视图需要将近一分钟的时间才能显示在屏幕上。

UIView 操作应该在主线程上完成 来自 doc

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.

如果你必须创建许多 UIView 对象,那么就这样做吧 dispatch_async() 但为此目的使用 main_queue。还有一件事,如果你想使用后台线程,那么考虑使用 CALayer 我们可以在后台线程

上完成大部分 CALayer 工作