【问题标题】:Swift 3 precise Timer repeating (iOS 9)Swift 3 精确计时器重复(iOS 9)
【发布时间】:2017-05-19 09:41:13
【问题描述】:

我有一个精确的计时器,需要每 40 毫秒更新一次(比可能的最精确)。在 iOS10 上很好(我使用新的 scheduleRepeating 方法),但在 iOS9 上我需要使用旧方法 (scheduledTimer) 并且非常滞后(有时 24 毫秒,有时是72...),所以我的硬件界面和视觉效果又滞后。

有什么建议吗?

func launchTimer() {
    if #available(iOS 10.0, *) {
            startTickTimer()
    } else {
        let timerQueue =  DispatchQueue(label: "my.queue.tickTimer", attributes: .concurrent)
        self.swiftTimer = Timer.scheduledTimer(timeInterval: period, target: self, selector: #selector(executeTimer), userInfo: nil, repeats: true)
        timerQueue.async {
            RunLoop.current.add(self.swiftTimer!, forMode: RunLoopMode.defaultRunLoopMode)
        }
    }
}

static func startTickTimer() {
    let queue = DispatchQueue(label: "my.queue.tickTimer", attributes: .concurrent)
    DMXTimer.tickTimer?.cancel()
    DMXTimer.tickTimer = DispatchSource.makeTimerSource(queue: queue)
    DMXTimer.tickTimer?.scheduleRepeating(deadline: .now(), interval: .milliseconds(40), leeway: .seconds(1))
    DMXTimer.tickTimer?.setEventHandler {
        executeTimer()
    }
    DMXTimer.tickTimer?.resume()
}

static func executeTimer() {
    print("hello moto")
}

【问题讨论】:

    标签: ios swift timer ios9 nstimer


    【解决方案1】:

    来自 Apple 文档关于 NSTimer:

    计时器不是实时机制。如果计时器的触发时间发生 在长时间运行循环标注期间或运行循环处于以下模式时 没有监控定时器,定时器直到下一次才会触发 运行循环检查计时器。因此,实际时间 计时器触发可能会明显延迟。另请参阅计时器容差。

    如果您想要一个非常精确的计时器,您可以检查 Apple Tech Note 的实现并适应 Swift 或使用 CADisplayLink 进行显示更新。

    【讨论】:

      【解决方案2】:

      我建议使用NSThread 并在内部循环而不是计时器。它更复杂,但恕我直言,它有更多的设置和灵活的行为

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-27
        • 2011-05-27
        • 1970-01-01
        • 2017-06-06
        • 1970-01-01
        • 2017-08-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多