KVO无法正常工作:已收到消息但未处理

时间:2016-09-22 23:39:47

标签: ios swift macos

玩KVO时出现以下错误。它只适用于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;
}

代码如下:

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

1 个答案:

答案 0 :(得分:1)

根据docs,方法的名称为observeValue(forKeyPath:of:change:context:)。请注意of:,而不是ofObject:。您的方法不是所需方法的实现。我相信你需要用override来标记正确命名的方法(并且编译器允许你在没有这个的情况下离开的事实表明你的名字有误)。