Skip to content

Instantly share code, notes, and snippets.

@salexkidd
Created January 24, 2018 08:07
Show Gist options
  • Save salexkidd/baf9b8a847fc6780db1e12c57c27c7db to your computer and use it in GitHub Desktop.
Save salexkidd/baf9b8a847fc6780db1e12c57c27c7db to your computer and use it in GitHub Desktop.
ちなみに UserDefaults.didChangeNotification だと1回しかきてないとかいいよる
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)
@salexkidd
Copy link
Author

Result:

TESTKEY changed: (1times)
TESTKEY changed: (2times)
Changed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment