diff --git a/AltStore/Operations/BackupAppOperation.swift b/AltStore/Operations/BackupAppOperation.swift index 2cf17266..27fbb793 100644 --- a/AltStore/Operations/BackupAppOperation.swift +++ b/AltStore/Operations/BackupAppOperation.swift @@ -29,6 +29,9 @@ class BackupAppOperation: ResultOperation private var appName: String? private var timeoutTimer: Timer? + private weak var applicationWillReturnObserver: NSObjectProtocol? + private weak var backupResponseObserver: NSObjectProtocol? + init(action: Action, context: InstallAppOperationContext) { self.action = action @@ -153,8 +156,11 @@ private extension BackupAppOperation { func registerObservers() { - var applicationWillReturnObserver: NSObjectProtocol! - applicationWillReturnObserver = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (notification) in + self.applicationWillReturnObserver = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (notification) in + defer { + self?.applicationWillReturnObserver.map { NotificationCenter.default.removeObserver($0) } + } + guard let self = self, !self.isFinished else { return } self.timeoutTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { [weak self] (timer) in @@ -166,18 +172,17 @@ private extension BackupAppOperation self.finish(.failure(OperationError.timedOut)) } } - - NotificationCenter.default.removeObserver(applicationWillReturnObserver!) } - var backupResponseObserver: NSObjectProtocol! - backupResponseObserver = NotificationCenter.default.addObserver(forName: AppDelegate.appBackupDidFinish, object: nil, queue: nil) { [weak self] (notification) in + self.backupResponseObserver = NotificationCenter.default.addObserver(forName: AppDelegate.appBackupDidFinish, object: nil, queue: nil) { [weak self] (notification) in + defer { + self?.backupResponseObserver.map { NotificationCenter.default.removeObserver($0) } + } + self?.timeoutTimer?.invalidate() let result = notification.userInfo?[AppDelegate.appBackupResultKey] as? Result ?? .failure(OperationError.unknownResult) self?.finish(result) - - NotificationCenter.default.removeObserver(backupResponseObserver!) } } }