何时对 SWIFT 中的 UI 更新使用线程

When to use threading for UI updates in SWIFT

我对何时将更新 UI 的代码放在主队列上感到困惑:

dispatch_async( dispatch_get_main_queue() )
{
     // Do UI update here
}

https://www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1 等在线资源建议使用该方法。但是,许多 swift/iOS 教程不应用该编码模式,尤其是涉及 UI 小更新时,例如 button.hidden = falsebutton.backgroundColor = UIColor.blueColor()

所有 UI 元素应在应用程序的 主线程 中更新。如果您想看到适当的过渡和顺利更新,这是一条黄金法则 ui.

如果您在主线程上工作,则无需使用:

dispatch_async( dispatch_get_main_queue() )
{
     // Do UI update here
}

因为你在应用程序的主线程中。

您需要使用在其他线程或其他操作中出现的代码块,并且需要在这些线程中更新 UI。

想象一下您需要在后台线程中进行一些计算并在此线程中更新 UI 的情况。

代码解决示例:

//Async operation in with we would like to do some calculation and do not block main thread of the application.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
       let result = doSomeCalculation()
       //After we receive result of the calculation we need to update UI element `UIlable` so we call main thread for that.
       dispatch_async(dispatch_get_main_queue()) {
                label.stringValue = result
       }
}