在特定日期使用Timer调用函数

问题描述 投票:0回答:1

我需要调用函数午夜前5分钟

仅在该时间段内用户在包含UIViewUICollectionView中,才调用该函数。

我需要此collectionView到reloadData() 午夜前5分钟

我想到使用NotificationCenter.default.addObserver观察者

如果您想使用NotificationCenter,什么是在午夜前5分钟收到通知的最佳方式?

您认为使用Timer而不是observer会更好吗?

其中哪些对应用程序性能更方便?

谢谢大家的帮助

ios swift uicollectionview nstimer nsnotificationcenter
1个回答
0
投票

阅读Alexander-Reinstate Monica建议后,我使用为特定日期编程的计时器找到了解决问题的方法

let date = Date().addingTimeInterval(5)
let timer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: .common)

解决方案在这里https://www.hackingwithswift.com/example-code/system/how-to-run-code-at-a-specific-time有很好的解释

© www.soinside.com 2019 - 2024. All rights reserved.