user3382170
user3382170

Reputation:

Using NSTimer in real time - Swift

I'm trying to figure out how to use NSTimer, in my case I need to use it in real time updating every second kind of like a clock. I have read the documentation but, I'm not really sure how to use it. I've seen other posts on here talking about setting a timer instead of setting the timer to the real time and counting up in real time from there.

Question: How do I go about this?

Upvotes: 2

Views: 2852

Answers (2)

Abizern
Abizern

Reputation: 150685

dispatch_timers are more accurate and a better way to fire events every second. NSTimer has an accuracy of 50-100 milliseconds. This could be too much for real time (see here).

Upvotes: 3

zisoft
zisoft

Reputation: 23078

According to the docs, a NSTimer may be inaccurate, it fires when the system is idle enough to do so.

What you can do if are really dependant on exact time values: Create a timer and let it fire once a second. In the fired method ask for the exact system time and do your processing with it. This way you get always accurate time values independent of the accuracy of the timer events.


Some sample code: It stores the system time of the timer start. In the update method compute the exact time difference since timer start. So you get accurate values.

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)

    ...
}

Upvotes: 3

Related Questions