-1

I have made a timer in xcode for an app, and I'm trying to average the times but in order to do that, I need to save the output string from NSTimer to a variable. I formatted it to have three strings that read as one, which looks like "00:00:00" with minutes, seconds, and milliseconds. How can I save the individual chunks as variables? I know how to use the substrings to isolate the pieces, I just need to save them as variables.

func updateTime() {
    var currentTime = NSDate.timeIntervalSinceReferenceDate()

    //Find the difference between current time and start time.
    var elapsedTime: NSTimeInterval = currentTime - startTime

    //calculate the minutes in elapsed time.
    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (NSTimeInterval(minutes) * 60)

    //calculate the seconds in elapsed time.
    let seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(seconds)

    //find out the fraction of milliseconds to be displayed.
    let fraction = UInt8(elapsedTime * 100)

    //add the leading zero for minutes, seconds and millseconds and store them as string constants
    let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
    let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
    let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction)

    //concatenate minuets, seconds and milliseconds as assign it to the UILabel
    timerLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
}

There's where I updated the time, not exactly sure what else you need to see.

shim
  • 9,289
  • 12
  • 69
  • 108

2 Answers2

0

You could use something like this to turn your timer string into an array of Ints

var values = map(split("12:34:56") { $0 == ":" }) { (str) -> Int in return str.toInt() ?? 0 }
Casey Fleser
  • 5,707
  • 1
  • 32
  • 43
0

Note, you shouldn't use NSTimer to count time. Set an NSDate when the timer starts, and use timeIntervalSinceDate against the current time (get from NSDate())

NSTimer is not accurate enough for timing

Then you can just split up the NSTimerInterval into the components you want, such as in this question

Community
  • 1
  • 1
shim
  • 9,289
  • 12
  • 69
  • 108
  • That's what I did, I got most of it from a tutorial. I have not used swift or xcode much at all, thus the confusion. – Alan Barnett Apr 28 '15 at 16:55
  • So what are you stuck on? – shim Apr 29 '15 at 01:47
  • I have the output (00:00:00). I want to save parts of it (the 00's, which would have times) as variables so I can do averaging across multiple times. I just need to save parts of a string as a variable. – Alan Barnett Apr 29 '15 at 06:59
  • You should have the NSTimeInterval from the difference in time in seconds. You can extract the milliseconds, seconds, minutes, hours, etc from that variable using the methods described in the linked question above. – shim Apr 29 '15 at 16:22