gpt4 book ai didi

swift - Firebase Swift 3.0 setValuesForKeysWithDictionary

转载 作者:搜寻专家 更新时间:2023-10-31 19:29:11 25 4
gpt4 key购买 nike

代码如下:

func observeMessages() {

let ref = FIRDatabase.database().reference().child("messages")
ref.observe(.childAdded, with: { (snapshot) in

if let dictionary = snapshot.value as? [String: AnyObject] {
let message = Message()
message.setValuesForKeys(dictionary)
self.messages.append(message)
//this will crash because of background thread, so lets call this on dispatch_async main thread
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}, withCancel: nil)

}

运行时崩溃如下:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'

请帮我解决这个问题。

最佳答案

问题是您的 Message 模型类与您试图通过 setValuesForKeys 方法放入其实例中的内容不匹配。您的字典与 Message 类不一致。

这就是错误消息告诉您的内容:您的应用试图为您的 snapshot.value 中的键设置一个值,该值在您的 Message 类中不存在。

检查 Message 类中的相同数量的同名属性是否与 snapshot.value 中的属性完全相同。

为避免不匹配,您可以这样定义您的 Message 类:

class Message: NSObject {

var fromId: String?
var text: String?
var timestamp: NSNumber?
var toId: String?
var imageUrl: String?
var imageWidth: NSNumber?
var imageHeight: NSNumber?

init(dictionary: [String: AnyObject]) {

super.init()
fromId = dictionary["fromId"] as? String
text = dictionary["text"] as? String
timestamp = dictionary["timestamp"] as? NSNumber
toId = dictionary["toId"] as? String
imageUrl = dictionary["imageUrl"] as? String
imageWidth = dictionary["imageWidth"] as? NSNumber
imageHeight = dictionary["imageHeight"] as? NSNumber
}

}

关于swift - Firebase Swift 3.0 setValuesForKeysWithDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40787591/

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