Using NSKeyValueObservation to observe value in Us

2019-04-07 14:19发布

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条回答
我只想做你的唯一
2楼-- · 2019-04-07 14:42

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

extension UserDefaults
{
    @objc dynamic var isRunningWWDC: Bool
    {
        return bool(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.set(true, forKey: "isRunningWWDC")
查看更多
登录 后发表回答