ios - 多线程 - 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
解决方案
这是因为您说更多代码不相关的部分需要时间。他们在每次调用之间花费时间和时间,asyncAfter
所以基本上.now()
变成了超过 1 秒前的东西。
无论如何,这不是实现它的传统方式。为此,您需要使用计时器。这是有关如何使用它的有用教程。Swift 中的计时器
推荐阅读
- docker - docker-compose python:无法打开文件'./main.py':[Errno 2]没有这样的文件或目录
- jquery - 即使我使用 Jquery 刷新或重新加载页面,如何在网页上保留来自输入标签的数据
- javascript - Discord.js Bot 赠品命令:embedSent.reactions.get 不是函数
- cluster-analysis - 如何使用 NS2 使用 TCL 脚本中的剩余能量值?
- excel - 刷新数据透视表
- javascript - 如何在 Electron Js 项目中使用母版页
- python - 如何在python中将标题添加到散景仪表板?
- android - 在 ANDROID 中使用 AsyncTask() 启动 AlertDialog 时如何避免应用程序崩溃?
- react-native - 嵌套在第一个模式堆栈导航器内的第二个堆栈导航器不起作用
- azure - 设置了 content-md5 的 Azure Blob 上传