【问题标题】:I can not stop Timer我无法停止计时器
【发布时间】:2017-01-09 09:58:20
【问题描述】:

我正在像这样创建计时器和循环。

private var iteration:Int = 0
private var syncTimer:Timer? = Timer()

//MARK: - Singleton
static let synchronizationInstance:DeviceSynchronization = DeviceSynchronization()
private init(){ 
}

public func synchronizeAllDevices(){         
        let when = DispatchTime.now() + 2
        DispatchQueue.main.asyncAfter(deadline: when) {
            self.syncTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(DeviceSynchronization.synchronizeDevices), userInfo: nil, repeats: true)
            self.syncTimer?.fire()
        }
    }
}

@objc private func synchronizeDevices(){
    if iteration >= 7 {
        syncTimer?.invalidate()
        syncTimer = nil
        iteration = 0
    } else {
        devicesList![iteration].synchroniseState()
        iteration += 1
    }
}

当它达到七次代表时,syncTimer?.invalidate()syncTimer = nil 应该停止 syncTimer 但没有任何反应。计时器仍然有效。不知道是不是bug。

【问题讨论】:

  • 您可能在代码中的某处再次被称为synchronizeAllDevices .invalidate() 应该可以正常工作
  • 就我上面显示的代码测试(我需要移动一个不平衡的右括号)而言,您的代码按预期工作。正如 Tj3n 建议的那样,您在隐藏的某个地方有一些故障。
  • 我不确定类 DeviceSynchronization 的实现在哪里,但乍一看似乎 #selector(DeviceSynchronization.synchronizeDevices) 应该是这样的:@987654328 @ 反而;但不清楚这个 sn-p 是否来自实际的 DeviceSynchronization 类。
  • 我将 #selector(DeviceSynchronization.synchronizationInstance.synchronizeDevices) 更改为 #selector(DeviceSynchronization.synchronizationInstance.synchronizeDevices) 但它仍然不起作用。
  • @WujoFefer,您可能需要发布完成的实现才能看到全貌,因为在我的测试类中,您的代码完美无缺,并且计时器在第 7 次迭代后停止;但是在我的测试类中,您的所有代码(原样)都在 DeviceSynchronization 类的实现中;但根本不清楚该类在您的屏幕上的外观。

标签: ios iphone swift swift3 ios10


【解决方案1】:

当应用程序连接到 Stream.Event.openCompleted 中的服务器时,我的同步代码开始。

internal func stream(_ aStream: Stream, handle eventCode: Stream.Event) {

    switch eventCode {
    case Stream.Event.openCompleted:
        log.info("The open has completed successfully.")
        reconnectCount = 0
        syncAllDevices.synchronizeAllDevices()
        break
    case Stream.Event.hasSpaceAvailable:
        log.info("The stream can accept bytes for writing.")
        break
    case Stream.Event.hasBytesAvailable:
        receveData()
        break
    case Stream.Event.errorOccurred:
        log.info("An error has occurred on the stream.")
        break
        reconnect()
    case Stream.Event.endEncountered:
        log.info("The end of the stream has been reached.")
        break
    default:
        log.info(„Unknown error”)
        break
    }
}

2 秒后,我尝试同步列表中的所有设备(对象)。 我发现这个事件被触发了两次,我不知道为什么,但这在单例中创建了 2 个计时器......

解决了! 我的问题是当 Stream.Event.openCompleted 触发两次时,这就是我的同步类创建两个计时器的原因...... 我通过创建一个真/假变量“isSyncIsInProgress”解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多