簡體   English   中英

實時使用NSTimer-Swift

[英]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)

    ...
}

dispatch_timers更精確,並且是每秒觸發事件的更好方法。 NSTimer的精度為50到100毫秒。 對於實時而言,這可能太多了(請參閱此處 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM