Reputation: 55715
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
//...
}
Upvotes: 9
Views: 6401
Reputation: 18998
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
Upvotes: 6