我在swift中做了一個計時器,它會每0.01秒更新一次GUI(不包含在代碼中)。在被重複調用的代碼中,我設置了當計時器達到目標時間時使計時器無效。我期待它在定時器完成之前不會返回到主函數,但是當定時器仍在運行時,main()函數上的命令仍將繼續執行。我已經將代碼壓縮成一個應該仍然會產生問題的小例子。如果有任何錯誤或您想要更多的代碼,請讓我知道。這裏是代碼:迅捷計時器延遲不會暫停執行
import UIKit
class TimerTestFile: UIViewController {
var dataObject: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
main()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func updateTime() {
let 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 strSeconds = String(format: "%02d", (UInt8(targetSeconds) - seconds))
if seconds == UInt8(targetSeconds) {
timer.invalidate()
}
/* --GUI ONLY-- timerLabel.text = strSeconds
let percentNum = (Float(seconds) + Float(fraction)/100)
print (percentNum)
let percent = Float(percentNum)/Float(targetSeconds)
print(percent)
progressBar.setProgress(Float(percent), animated: true) */
}
func Timer(Seconds: Int) {
progressBar.setProgress(0.0, animated: false)
targetSeconds = Seconds
let aSelector : Selector = #selector(TimerTestFile.updateTime)
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
func main() {
Timer(5)
//This timer is not delayed until the proir is done
Timer(5)
}
}