I have an application using NSTimer in centisecond (0.01 seconds) to display the current stopwatch in String Format as 00: 00.00 (mm: ss.SS). (Basically, cloning the iOS built-in stopwatch to integrate into real-time math problems with math time, perhaps in the future, accuracy in milliseconds is required)
I am using (misuse?) NSTimer to force an update to UILabel. If the user clicks the Start button, this is the NSTimer code used to start repeating the function:
displayOnlyTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("display"), userInfo: nil, repeats: true)
And here is the function executed by the above NSTimer:
func display() { let currentTime = CACurrentMediaTime() - timerStarted + elapsedTime if currentTime < 60 { timeDisplay.text = String(format: "%.2f", currentTime) }else if currentTime < 3600 { var minutes = String(format: "%00d", Int(currentTime/60)) var seconds = String(format: "%05.2f", currentTime % 60) timeDisplay.text = minutes + ":" + seconds }else { var hours = String(format: "%00d", Int(currentTime/3600)) var minutes = String(format: "%02d", (Int(currentTime/60)-(Int(currentTime/3600)*60))) var seconds = String(format: "%05.2f", currentTime % 60) timeDisplay.text = hours + ":" + minutes + ":" + seconds } }
At the same time, at least 2 displayed links will work. Will this method be too inefficient when all other elements will play?
The display is then updated without using NSTimer when the user presses stop / pause / reset. I did not find anything that directly translated into Swift. I am pretty sure that I am using an inefficient method to quickly update UILabel text in a UIView.
More: I am working on less messy code for the start timer format (mm: ss.SS). I will update it again when we finish this.
UPDATE: Thanks to Rob and jtbandes for answering both of my questions (formatting method and display mapping method). It was easy to replace NSTimer (see above) with CADisplayLink ():
displayLink = CADisplayLink(target: self, selector: Selector("display")) displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
And then replace all code instances
displayOnlyTimer.invalidate()
with
displayLink.paused = true
(this will pause the display of the image link)