|
13 | 13 |
|
14 | 14 | import Foundation
|
15 | 15 |
|
16 |
| -/// Watches for changes to UserDefaults using old-school Key-Value Observing. |
| 16 | +/// Watches for changes to `UserDefaults` using old-school Key-Value Observing. |
17 | 17 | ///
|
18 |
| -/// KVO allows us to be notified of changes from anywhere (including other processes), not just via the property wrapper's setter. |
| 18 | +/// KVO allows us to be notified of changes from anywhere (including other processes), |
| 19 | +/// not just via the property wrapper's setter. |
19 | 20 | ///
|
20 |
| -/// We can't use Swift's block-based KVO because that requires a KeyPath, which we cannot create from a String. |
| 21 | +/// We can't use Swift's block-based KVO because that requires a `KeyPath`, |
| 22 | +/// which we cannot create from a `String`. |
21 | 23 | final class ObserverTrampoline: NSObject {
|
22 | 24 | private let userDefaults: UserDefaults
|
23 | 25 | private let key: String
|
24 |
| - private let block: () -> Void |
| 26 | + private let action: () -> Void |
25 | 27 |
|
26 |
| - init(userDefaults: UserDefaults, key: String, block: @escaping () -> Void) { |
27 |
| - assert(!key.hasPrefix("@"), "Cannot observe a user default key starting with '@'") |
28 |
| - assert(!key.contains("."), "Cannot observe a user default key containing '.'") |
| 28 | + init(userDefaults: UserDefaults, key: String, action: @escaping () -> Void) { |
| 29 | + assert(!key.hasPrefix("@"), "Error: key name cannot begin with a '@' character and be observed via KVO.") |
| 30 | + assert(!key.contains("."), "Error: key name cannot contain a '.' character anywhere and be observed via KVO.") |
29 | 31 | self.userDefaults = userDefaults
|
30 | 32 | self.key = key
|
31 |
| - self.block = block |
| 33 | + self.action = action |
32 | 34 | super.init()
|
33 |
| - |
34 | 35 | userDefaults.addObserver(self, forKeyPath: key, context: nil)
|
35 | 36 | }
|
36 | 37 |
|
37 |
| - override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { |
38 |
| - block() |
| 38 | + deinit { |
| 39 | + self.userDefaults.removeObserver(self, forKeyPath: self.key, context: nil) |
39 | 40 | }
|
40 | 41 |
|
41 |
| - deinit { |
42 |
| - userDefaults.removeObserver(self, forKeyPath: key, context: nil) |
| 42 | + // swiftlint:disable:next block_based_kvo |
| 43 | + override func observeValue( |
| 44 | + forKeyPath keyPath: String?, |
| 45 | + of object: Any?, |
| 46 | + // swiftlint:disable:next discouraged_optional_collection |
| 47 | + change: [NSKeyValueChangeKey: Any]?, |
| 48 | + context: UnsafeMutableRawPointer?) { |
| 49 | + self.action() |
43 | 50 | }
|
44 | 51 | }
|
0 commit comments