[英]Using NSTimer in real time - Swift
我試圖弄清楚如何使用NSTimer,就我而言,我需要實時使用它,就像時鍾一樣,每秒更新一次。 我已經閱讀了文檔,但是我不確定如何使用它。 我在這里看到過其他文章,它們談論設置計時器而不是將計時器設置為實時並從那里實時計數。
問題:我該怎么做?
根據文檔,NSTimer可能不准確,它會在系統空閑時觸發。
如果確實取決於確切的時間值,該怎么辦:創建一個計時器,使其每秒觸發一次。 在解雇方法中,詢問確切的系統時間並進行處理。 這樣,您始終可以獲得准確的時間值,而與計時器事件的准確性無關。
一些示例代碼:它存儲計時器啟動的系統時間。 在update
方法中,計算自計時器啟動以來的確切時間差。 這樣您可以獲得准確的值。
var timer: NSTimer?
var timerStart: NSDate?
func startTimer() {
// get current system time
self.timerStart = NSDate()
// start the timer
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update:"), userInfo: nil, repeats: true)
}
func update() {
// get the current system time
let now = NSDate()
// get the seconds since start
let seconds = now.timeIntervalSinceDate(self.timerStart)
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.