Код: Выделить всё
@MainActor
open class TimerScheduler {
private enum TimerState {
case normal
case paused(remaining: TimeInterval)
}
private struct TimerInfo {
let timer: Timer
let state: TimerState
}
private var keyToTimerInfoMap = [String:TimerInfo]()
private let lifecycleChecker: () -> Bool
public init(lifecycleChecker: @escaping @MainActor () -> Bool = { true }) {
self.lifecycleChecker = lifecycleChecker
// Note: When app is in background, NSTimer will only get a few minutes of execution.
// Then the timer will be paused
// These notifications are there to ensure NSTimer is paused immediately when app goes background.
NotificationCenter.default.addObserver(self, selector: #selector(pause), name:UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(resume), name:UIApplication.didBecomeActiveNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
for (_, info) in keyToTimerInfoMap {
info.timer.invalidate()
}
}
private func unschedule(key: String) {
guard let info = keyToTimerInfoMap[key] else { return }
info.timer.invalidate()
keyToTimerInfoMap.removeValue(forKey: key)
}
// other functions
}
< /code>
У меня есть предупреждение: < /p>
Не может получить доступ к свойству 'keytotimerinfomap' с неопощими типом '[String: timerscheduler.timerinfo]' из неизолированного Deinit; Это ошибка в языковом режиме Swift 6
Это разумно, потому что Deinit Код: Выделить всё
deinit {
NotificationCenter.default.removeObserver(self)
Task { @MainActor in
for (_, info) in keyToTimerInfoMap {
info.timer.invalidate()
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... -in-deinit
Мобильная версия