我将此代码用于后台工作:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, {
// Some work in the background and updating UI too.
});
然而我正在阅读here我们应该使用:
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
}
更新用户界面时。 我的问题是:在我使用的代码示例中,UI 在全局队列中得到更新并且 UI 更新时没有错误。我使用的方法与上面链接中提到的方法有什么区别?
P.S: 代码在 Mac OS X 10.10 上执行
最佳答案
Thread Safety Summary在里面 “线程编程指南”指出:
Main Thread Only Classes
The following classes must be used only from the main thread of an application.
NSCell
and all of its descendantsNSView
and all of its descendants. For more information, see NSView Restrictions.
绑定(bind)到主线程的唯一调度队列是
使用 dispatch_get_main_queue()
获得的主队列。
dispatch_get_global_queue()
返回一个全局并发队列
它不是主队列,因此可以执行它的工作
在辅助线程上。因此从这个队列更新 UI
可能偶然工作,但它也可能导致 UI 更新延迟,
非工作 UI 更新或崩溃。
关于multithreading - 从后台线程 SWIFT 更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28137380/