我知道Timer
不能保证完全按照您要求的速度运行。
但是,我刚刚开始了一个全新的项目:
class ViewController: NSViewController {
var timer = Timer()
var count: Double = 0.0
var timeStamp: Date = Date()
override func viewDidLoad() {
super.viewDidLoad()
self.timer = Timer.scheduledTimer(timeInterval: 0.1,target: self,selector: #selector(self.updateCounting),userInfo: nil,repeats: true)
}
@objc func updateCounting(){
let duration = self.timeStamp.distance(to: Date())
print("Counting \(self.count) vs. Real life \(duration)")
self.count = self.count + 0.1
}
}
我期望在count
和duration
之间得到大致相同的结果,但是我看到类似这样的奇怪事情:
Counting 60.50000000000059 vs. Real life 60.64057409763336
Counting 60.60000000000059 vs. Real life 60.741435050964355
Counting 60.70000000000059 vs. Real life 70.84065008163452
Counting 60.800000000000594 vs. Real life 80.94094407558441
Counting 60.900000000000595 vs. Real life 82.99448704719543
在iMac和MacBook Pro的Xcode 11.5上进行了测试。 我在这里做错什么了吗?