Using NSKeyValueObservation to observe value in UserDefaults

倾然丶 夕夏残阳落幕 提交于 2019-12-05 22:24:26

问题


I would like to use the block-based KVO from Swift 4 to observe changes to a value in UserDefaults. I am able to do this for observing a key path for WKWebView's estimatedProgress but haven't been successful with UserDefaults because the provided key path isn't what it's looking for. Providing just a String isn't enough (Generic parameter 'Value' could not be inferred), prefixing it with \ isn't enough (Type of expression is ambiguous without more context). What's the correct way to create the KeyPath to observe a value in UserDefaults?

observerToken = UserDefaults.standard.observe("myvalue") { (object, change) in
    //...
}

回答1:


Yes its possible.First of all you need to define keypath as

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

And use that keypath for block based KVO as

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

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

}
UserDefaults.standard.isRunningWWDC = true


来源:https://stackoverflow.com/questions/44424971/using-nskeyvalueobservation-to-observe-value-in-userdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!