Swift定时器延迟不暂停执行

时间:2016-07-26 18:05:02

标签: swift timer

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


}

1 个答案:

答案 0 :(得分:0)

计算机能够以每毫秒(0.01秒)一个命令的速度执行任务。

首先,您安排计时器,它将在0.01秒内首先启动。在此期间,执行返回到之前发生的任何事情(Timer方法然后返回到main方法。)当Timer启动时,一旦完成,还有几微秒计算机可以利用在主线程上运行其他代码。

故事的道德是,在你的Timer未被触发的那些时间间隔内,执行返回其他地方。

此外,如果您需要此GUI在用户与UI交互时仍然更新,例如当它们滚动或类似时,您需要将NSTimer显式添加到主运行循环中使用初始化程序而不是scheduledTimer方法创建公共模式之后的常见模式,如here所述(尽管在Objective-C中)。

旁注: 考虑更改Timer方法。在即将推出的Foundation版本中,NSTimer已在Swift中重命名为Timer,您的函数类似于初始化程序。此外,Swift中的方法名称和属性应为小写。