lkahtz lkahtz - 1 year ago 218
iOS Question

KVO not working: message was received but not handled

I got the following error when playing around with KVO. Does it only work with subclasses of UIViewController?

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '<sort.object: 0x100a074e0>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: name
Observed object: <sort.User: 0x100a06bb0>
Change: {
kind = 1;
new = Test;

The code are as below:

import Foundation

class User: NSObject {
dynamic var name: String?

class object: NSObject {
func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutableRawPointer) {
print("Name changed")

var user = User()
var ob = object()
user.addObserver(ob, forKeyPath: "name", options:, context: nil) = "Test"

try = "Test 2"
user.removeObserver(ob, forKeyPath: "name")

Answer Source

According to the docs, the name of the method is observeValue(forKeyPath:of:change:context:). Note of:, not ofObject: as you have. Your method is not an implementation of the required method. I believe you'll need to mark the properly-named method with override (and the fact that the compiler let you get away without that was a sign that you had the name wrong).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download