Created
January 24, 2018 08:07
-
-
Save salexkidd/baf9b8a847fc6780db1e12c57c27c7db to your computer and use it in GitHub Desktop.
ちなみに UserDefaults.didChangeNotification だと1回しかきてないとかいいよる
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 userDefaults: UserDefaults = UserDefaults.standard | |
let defaultCenter: NotificationCenter = NotificationCenter.default | |
// Remove Perferences & register default | |
userDefaults.removePersistentDomain(forName: Bundle.main.bundleIdentifier!) | |
userDefaults.register(defaults: [testKey : false]) | |
class testClass: NSObject { | |
var callCount: Int = 0 | |
override init() { | |
super.init() | |
userDefaults.addObserver(self, forKeyPath: testKey, options: .new, context: nil) | |
defaultCenter.addObserver( | |
self, | |
selector: #selector(userDefaultsDidChange), | |
name: UserDefaults.didChangeNotification, | |
object: nil | |
) | |
} | |
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { | |
self.callCount += 1 | |
if (keyPath == testKey) { | |
print("\(testKey) changed: (\(self.callCount)times)") | |
} | |
} | |
@objc func userDefaultsDidChange(_ notification: Notification) { | |
print("Changed!") | |
} | |
} | |
let testObj = testClass() | |
userDefaults.set(true, forKey: testKey) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: