我正在创建这样的计时器和循环。
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
但没有任何反应。计时器仍然有效。我不知道这里有错误。
答案 0 :(得分:0)
当应用程序连接到服务器时,我的同步代码开始在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"。