首页 > 解决方案 > 多线程 - Swift 中的 DispatchQueue asyncAfter 延迟

问题描述

我正在使用以下代码每秒定期调用一个函数。问题是延迟实际上是 1.1 秒,并且最终会越来越漂移,这可以在 NSLogs 中看到(并且它在代码的其他部分以及除了 NSLog 之外的其他部分中也可见)。我做错了吗,还是应该使用计时器?

private func updateTimeCode() {
    NSLog("Updating time")
    //Some more code that doesn't take time
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
        [weak self] in
            self ? .updateTimeCode()
    }
}
 019-08-06 17:15:19.713234+0530 MyApp-Swift[8299:2685215] Updating time

 2019-08-06 17:15:20.812652+0530 MyApp-Swift[8299:2685215] Updating time

 2019-08-06 17:15:21.913188+0530 MyApp-Swift[8299:2685215] Updating time

 2019-08-06 17:15:23.028814+0530 MyApp-Swift[8299:2685215] Updating time

标签: iosswiftgrand-central-dispatchdispatch-queue

解决方案


这是因为您说更多代码不相关的部分需要时间。他们在每次调用之间花费时间和时间,asyncAfter所以基本上.now()变成了超过 1 秒前的东西。

无论如何,这不是实现它的传统方式。为此,您需要使用计时器。这是有关如何使用它的有用教程。Swift 中的计时器


推荐阅读