Timer.scheduledTimer没有触发

时间:2018-06-12 22:12:16

标签: swift scenekit nstimer

我正在计算车辆在两个检查站之间行驶的时间。我已经设置了以下计时器来实现这一目标。

func startTimer() {
    if hasStarted == true && timerStarted == false {
        print("Timing started!")
        gameTimer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: (#selector(activeTiming)), userInfo: nil, repeats: true)
        timerStarted = true
    }
}

@objc func activeTiming() {
    print("Active timing block")
    if(hasFinished == false) {
        gameTime = gameTime + 0.001
        print("Add time succeeded")
    } else {
        gameTimer?.invalidate()
    }
}

预期输出如下:

Timing started!
Active timing block
Add time succeeded
Add time succeeded ... etc

实际输出:

Timing started!

因此看起来正确调用了startTimer但是定时器没有触发activeTiming代码块。任何建议都会非常有帮助。感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

发布此代码就像我正在使用的那样,但我不是Swift的专家,所以你的里程可能会有所不同!

class PerformanceTest {
    var name:           String = ""
    var tolerance:      Int64 = 0
    var lastTime:       Int64 = 0
    var thisTime:       Int64 = 0
    var delta:          Int64 = 0
    var percent:        Float = 0

    func setTolerance(vName: String, vTolerance: Int64) {
        name = vName
        tolerance = vTolerance
    }

    func reset() {
        delta = 0
        percent = Float((Float(delta) / Float(tolerance))) * 100
        //high = 0
    }

    func start() {
        lastTime = Date().toMillis()
    }

    func finish() {
        thisTime = Date().toMillis()
        let vDelta = thisTime - lastTime
        if(vDelta > delta) {
            delta = vDelta
            percent = Float((Float(delta) / Float(tolerance))) * 100
            if(delta > tolerance) {
                print("Performance Indicator: \(name) Above Tolerance" + String(format: "%3.0f", percent) + "%")
            }
        }
    }

    func display() -> String {
        //high = delta
        //print("\(vString) Tolerance: \(tolerance) Max: \(high)")
        return String(format: "%3.0f", percent) + "%  |"
    }
   }

extension Date {
    func toMillis() -> Int64! {
        return Int64(self.timeIntervalSince1970 * 1000)
    }

用法:

var performanceDefenseLoop = PerformanceTest()
performanceDefenseLoop.setTolerance(vName:  "DefenseLoop", vTolerance: 150)

func timeToUpdateDefenses()
{
    performanceDefenseLoop.start()
    defesensesLoop()
    performanceDefenseLoop.finish()
    print("\(performanceDefenseLoop.Display())"
}

//要重置 performanceDefenseLoop.reset()

请务必在主线程中启动计时器!

答案 1 :(得分:1)

您的代码适用于我,但这不是您想要为某个活动计时的方式,因为Timer并不准确,并且您浪费了大量的计算时间(阅读电池) )。

相反,我建议采用以下方法:

当事件开始时,记录开始时间:

let startTime = Date()

当事件结束时,计算经过的时间:

let elapsedTime = Date().timeIntervalSince(startTime)

elapsedTime将在几秒钟内(包括小数秒)。