func observeMessages(){
let ref = Database.database().reference().child("messages")
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
let message = Message()
print(dictionary)
message.setValuesForKeys(dictionary)
self.messages.append(message)
DispatchQueue.main.async { self.tableView.reloadData() }
}
}, withCancel: nil)
}
这是我的 Firebase&swift 项目的一部分。每次尝试调用 message.setValuesForKeys(dictionary) 时,我都会崩溃。
控制台的错误信息是
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key toId
我查了字典,里面有我想要的数据。我不知道我还能检查什么。我试图将“snapshot.value”更改为“snapshot.children.allobjects”,但由于该更改,我无法访问字典中的数据。
最佳答案
我的第一个猜测是你的一个 firebase 节点有一个在你的类中不存在的键
由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[setValue:forUndefinedKey:]: 此类与键 toId 的键值编码不兼容
^^^^
这是一个很好的线索。
检查您的 firebase 中的节点并确保它们都有一个键 toId 并且您的类也有一个 toId 属性。
key 不匹配会导致此问题。
此外,如果您想使用 setObjectForValue,则 Message 对象应继承自 NSObject(符合键值编码)
Objects typically adopt key-value coding when they inherit from NSObject (directly or indirectly), which both adopts the NSKeyValueCoding protocol and provides a default implementation for the essential methods
如果您已经检查以确保您的 key 全部匹配,那么它可能是 Message 对象的定义方式。它应该看起来像这样,确保它是一个 NSObject 并且键(属性)以 @objc
开头class Message: NSObject {
@objc var name = ""
@objc var toId = ""
}
我的最后一个建议是让你的代码变得 Swifty,不要依赖 NSObject。
class Message {
var name = ""
var toId = ""
func initMessageWithSnap(aSnapshot: Snapshot) {
//desconstuct the snapshot and assign the vars
}
}
关于swift - Snapshot.value 在 setValueForKeys 上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077952/