Using NSKeyValueObservation to Observe a Value in UserDefaults

I would like to use block-based KVOs from Swift 4 to observe value changes in UserDefaults. I can do this to observe the key path for WKWebView estimatedProgress, but was not successful with UserDefaults, because the provided key path is not what it is looking for. Providing just a string is not enough (the general parameter "Value" cannot be inferred), prefixing it with is \not enough (the type of expression is ambiguous without additional context). What is the correct way to create KeyPathto observe the value in UserDefaults?

observerToken = UserDefaults.standard.observe("myvalue") { (object, change) in
    //...
}
+6
source share
1

, . , keypath

extension UserDefaults
{
    @objc dynamic var isRunningWWDC: Bool
    {
        get {
            return bool(forKey: "isRunningWWDC")
        }
        set {
            set(newValue, forKey: "isRunningWWDC")
        }
    }
}

KVO

var observerToken:NSKeyValueObservation?
observerToken = UserDefaults.standard.observe(\.isRunningWWDC, options:[.new,.old])
{ (object, change) in

    print("Change is \(object.isRunningWWDC)")

}
UserDefaults.standard.isRunningWWDC = true
+3

Source: https://habr.com/ru/post/1678747/


All Articles