3

I'm trying to make a timer showing the following - hours : minutes : seconds : milliseconds. Here is my code:

var timer = NSTimer()
var startTime = NSTimeInterval()

func updateTime()
{
    var currentTime = NSDate.timeIntervalSinceReferenceDate()
    var elapsedTime : NSTimeInterval = currentTime - startTime

    let hours = UInt8(elapsedTime / 3600.0)
    elapsedTime -= (NSTimeInterval(hours) * 3600)

    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (NSTimeInterval(minutes) * 60)

    let seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(seconds)

    let fraction = UInt8(elapsedTime * 100)

    let strHours = String(format: "%02d", hours)
    let strMinutes = String(format: "%02d", minutes)
    let strSeconds = String(format: "%02d", seconds)
    let strFraction = String(format: "%02d", fraction)

    timeLabel.text = "\(strHours):\(strMinutes):\(strSeconds):\(strFraction)"
}

@IBAction func start(sender: AnyObject) {
    if !timer.valid {
        let aSelector : Selector = “updateTime”
        timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
        startTime = NSDate.timeIntervalSinceReferenceDate()
    }
}

How can I add 5 seconds to the timer in another method? (Obviously I will have to make a global var, but I'm trying to keep it simple for now and first actually add the 5 secs, then we'll worry about the global part.) I tried changing/adding the following:

var seconds = UInt8(elapsedTime)
seconds += 5 // Error here...
elapsedTime -= NSTimeInterval(seconds)

But I get an error saying:

fatal error: floating point value can not be converted to UInt8 because it is less than UInt8.min

What's the correct way to add 5 seconds to the timer?

Horay
  • 1,388
  • 2
  • 19
  • 36

1 Answers1

3

Invalidate the timer, then create a new one. You can't modify the time interval of a timer.

As far as your error, elapsedTime is probably negative, which yields the error. UInt8.min is 0.

A timer is not a stop watch. An NSTimer fires off at a specific time.

For something like a stop watch, you should simply be setting a start date. Then, you could use a timer that's set to one second to update the display every second. You'd display the difference between the current time and the start date.

Marcus Adams
  • 53,009
  • 9
  • 91
  • 143
  • Thanks for the answer! It sounds right! How can I retrieve the value of the original timer, then assign the same time to a new one, and add 5 sec? – Horay Aug 20 '15 at 20:38
  • Im confused. Isn't that what I did at the first 2 lines of func updateTime()? – Horay Aug 20 '15 at 20:57