从后台线程SWIFT更新UI [英] Updating UI from background thread SWIFT

查看:77
本文介绍了从后台线程SWIFT更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码进行后台工作:

I'm using this code for background work:

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, {
        // Some work in the background and updating UI too.
    });

但是我正在阅读此处,我们应该使用:

However I was reading here that we should use:

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会在全局队列中更新,并且UI会更新而不会出现错误.我使用的方法与上面的链接中提到的方法有什么区别?

when updating UI. My question is: In the code sample I am using the UI gets updated in the global queue and UI is updated without errors. What is the difference between the approach I am using, and the approach mentioned in the link above?

P.S:代码在Mac OS X 10.10上执行

P.S: the code is executed on Mac OS X 10.10

推荐答案

线程安全摘要" 线程编程指南"指出:

Thread Safety Summary in the "Threading Programming Guide" states:

仅主线程类

以下类必须仅在主线程的主线程中使用 应用程序.

The following classes must be used only from the main thread of an application.

  • NSCell及其所有后代
  • NSView及其所有后代. 有关更多信息,请参见NSView限制.
  • NSCell and all of its descendants
  • NSView and all of its descendants. For more information, see NSView Restrictions.

绑定到主线程的唯一调度队列是 您通过dispatch_get_main_queue()获得的主队列.

The only dispatch queue that is bound to the main thread is the main queue that you get with dispatch_get_main_queue().

dispatch_get_global_queue()返回全局并发队列 不是主要队列,因此可以执行其工作 在辅助线程上.因此,从此队列更新UI 可能是偶然的,但也会导致UI更新延迟, 无效的用户界面更新或崩溃.

dispatch_get_global_queue() returns a global concurrent queue which is not the main queue, and therefore may execute its work on secondary threads. Therefore updating the UI from this queue may work by chance, but it can also cause delayed UI updated, non-working UI updates or crashes.

这篇关于从后台线程SWIFT更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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