2016-07-26 31 views
0

我在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) 
} 


} 

回答

0

計算機能夠比每個毫秒(0.01秒)一個命令更快地執行任務。

首先,您安排計時器,該計時器首先在0.01秒內觸發。與此同時,執行返回到之前發生的任何事情(Timer方法,然後返回到main方法。)當Timer啓動時,一旦完成,計算機可能會利用另外幾個微秒來運行其他代碼在主線程上。

這個故事的寓意是,在你的定時器沒有開火的時候,執行回到其他地方。另外,如果你需要這個GUI在用戶與UI交互時仍然更新,例如當他們滾動或類似的時候,你需要明確地將你的NSTimer添加到具有普通模式的主運行循環之後使用初始化器而不是scheduledTimer方法創建它,如here(儘管在Objective-C中)所述。

邊注: 考慮更改您的Timer方法。在即將推出的版本Foundation中,NSTimer已在Swift中重命名爲Timer,並且您的函數看起來像是一個初始化器。此外,方法名稱和屬性在Swift中應該是小寫的。