ios - 我无法停止计时器

标签 ios iphone swift swift3 ios10

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

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,但什么也不会发生。计时器仍然有效。我不知道这是错误。

最佳答案

当应用程序在 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”解决了这个问题。

关于ios - 我无法停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41545277/

相关文章:

ios - 如何在 Cordova 中从 CDVPlugin 显示 ViewController?

ios - 登录 Twitter 有时会失败

iphone - Core Data性能deleteObject并保存托管对象上下文

ios - 自定义标签栏 Swift

ios - UITableView插入行装饰

iphone - 使 UIButton 在旋转期间保持附着在页脚上

ios - 随着 iOS 13 的发布, "Sign in with Apple"是强制性的

ios - 如何计算 NSDictionary 对象的总大小?

ios - UIDocumentInteractionController 旋转后消失

iphone - 如何在 ios 中将变量从一个 Controller 传递到另一个 Controller ?