KVO无法正常工作:已收到邮件但未处理 [英] KVO not working: message was received but not handled
本文介绍了KVO无法正常工作:已收到邮件但未处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
玩KVO时出现以下错误。它是否仅适用于UIViewController的子类?
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;
}
代码如下:
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")
推荐答案
根据 docs ,方法的名称是 observeValue(forKeyPath:of:change:context:)
。注意:
,而不是 ofObject:
。您的方法不是所需方法的实现。我相信你需要用覆盖
来标记正确命名的方法(以及编译器让你逃脱的事实,如果没有这个,就表明你的名字错了)。
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).
这篇关于KVO无法正常工作:已收到邮件但未处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文