lkahtz lkahtz - 2 months ago 23
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: NSKeyValueObservingOptions.new, context: nil)

user.name = "Test"

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

Answer

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).