gpt4 book ai didi

ios - KVO 不工作 : message was received but not handled

转载 作者:行者123 更新时间:2023-11-28 16:10:18 44 4
gpt4 key购买 nike

我在使用 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")

最佳答案

根据docs ,方法的名称是 observeValue(forKeyPath:of:change:context:)。请注意 of:,而不是您所拥有的 ofObject:。您的方法不是所需方法的实现。我相信您需要使用 override 标记正确命名的方法(事实上,编译器让您在没有覆盖的情况下逃脱,这表明您的名称有误)。

关于ios - KVO 不工作 : message was received but not handled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39650439/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com