zumzum
zumzum

Reputation: 20238

was sent to an object that is not KVC-compliant for the "com" property

I want to observe the value stored in UserDefaults.standard under the key: com.apple.configuration.managed, so I did this:

UserDefaults.standard.addObserver(self, forKeyPath: "com.apple.configuration.managed", options: [.new, .old], context: nil)

I then implemented this:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

}

When I run the app observeValue... is never called when that default is changed, instead Xcode crashes with this error:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ addObserver: forKeyPath:@"com.apple.configuration.managed" options:1 context:0x0] was sent to an object that is not KVC-compliant for the "com" property.'

What's the right way of observing com.apple.configuration.managed in the UserDefaults.standard?

Upvotes: 3

Views: 2162

Answers (1)

Paulw11
Paulw11

Reputation: 114992

You can use KVC observing to observe properties of an object, and you can use KVC observing to observe the values that you assign to UserDefaults, but you cannot use KVC to observe a value where the value identifier contains periods, since this is used to describe a hierarchical keypath.

So, the exception message is correct, UserDefaults is not KVC compliant for the com property; what you have asked is to be notified when the managed property of the object referred to by the configuration property of the object referred to by the apple property of the object referred to by the com property of the UserDefaults object is modified.

So you can use KVC to be notified when "MyDefault" changes but not when "My.Default" changes. If you can't change the name of your user default then you will need to observe the NSUserDefaultsDidChangeNotification Notification

Upvotes: 4

Related Questions