【问题标题】:Best/most common way to update UI from background thread [closed]从后台线程更新 UI 的最佳/最常用方法 [关闭]
【发布时间】:2016-08-10 09:55:53
【问题描述】:

每次我需要退出关闭以更新 UI 时,我都会向 NSNotficiationCenter 发布通知,但这开始变得有点乏味,让我想知道是否有更好的方法。经过快速搜索,我发现您可以像这样分派到主队列:

dispatch_async(dispatch_get_main_queue()) {
    // update some UI
}

这种方法肯定会减少代码,但我想知道它是否提高了可读性。所以我的问题是,在 Swift 中从后台线程更新 UI 被认为是“要走的路”?

【问题讨论】:

  • 我认为这没有“一条路”(至少在 api 方面),但您在这里展示的内容很常见。有几个开源助手可以包装 gcd 调用并添加一些语法糖。 Here is one of them
  • 这比通知便宜得多,而且更清晰

标签: ios swift multithreading user-interface nsnotificationcenter


【解决方案1】:

这是要走的路:

let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
   // do some background task
   dispatch_async(dispatch_get_main_queue()) {
      // update some UI
   }
}

【讨论】:

  • 还考虑到这比@PEEJWEEJ 在我的问题下说的便宜得多,我会接受这个。
猜你喜欢
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 2012-04-24
  • 2010-09-07
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多