【问题标题】:Swift - Update labels in realtimeSwift - 实时更新标签
【发布时间】:2018-07-13 08:31:42
【问题描述】:

我有一组复杂的数学运算,需要几秒钟的时间(在速度更快的 iPhone 上是这样)。为了让用户感兴趣并相信程序没有小睡,我需要实时更新标签/数字。

从历史上看,我会使用:

    DispatchQueue.main.sync {...

但现在运行时会出现 Thread 1 错误。 所以我正在使用:

    DispatchQueue.global().async(execute: {
        DispatchQueue.main.sync {
            self.dateLabel.text = date1Formatter.string(from: newDate!)
            // etc
        }
     })

惊奇,惊奇这不是实时更新数字,只是在周期结束时。我如何“同步”它?

【问题讨论】:

  • 使用“异步”而不是“同步”。

标签: swift dispatch-queue


【解决方案1】:

您根本不应该调用 main.sync。 只需调用 DispatchQueue.main.async Ashley Mills 说:

    DispatchQueue.global().async(execute: {
        DispatchQueue.main.async {
            self.dateLabel.text = date1Formatter.string(from: newDate!)
            // etc
        }
     })

【讨论】:

  • 中间队列的意义何在?只需调用DispatchQueue.main.async 就足够了(因为 main 已经是一个串行队列)
  • 如果他想在循环中使用它并且不阻塞执行,则需要它。如果不是 - 你是对的。
  • 只调用DispatchQueue.main.async 不会阻塞执行
  • 太好了,所以它现在不在主队列中,但标签在循环完成之前不会更新。有什么想法吗?
  • 已通过这些更新进行了更改,但屏幕仍然没有更新,直到循环结束而不是每次传递结束?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多