Last active
May 14, 2020 05:45
-
-
Save salexkidd/eab683f34a536cf16cfd209625995ba5 to your computer and use it in GitHub Desktop.
UserDefaults.standard.addObserver calling observeValueForKeyPath multiple times
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
let testKey: String = "TESTKEY" | |
let defaults: UserDefaults = UserDefaults.standard | |
// Remove Perferences & register default | |
defaults.removePersistentDomain(forName: Bundle.main.bundleIdentifier!) | |
defaults.register(defaults: [testKey : false]) | |
class testClass: NSObject { | |
var callCount: Int = 0 | |
override init() { | |
super.init() | |
defaults.addObserver(self, forKeyPath: testKey, options: .new, context: nil) | |
} | |
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { | |
self.callCount += 1 | |
print("Hello World: (\(self.callCount)times)") | |
} | |
} | |
let testObj = testClass() | |
defaults.set(true, forKey: testKey) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thx for Replying!