Firebase Swift 3.0 setValuesForKeysWithDictionary

4
这里是代码:
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)

}

运行时,它会崩溃并显示以下信息:

终止应用程序,原因是未捕获的异常 'NSUnknownKeyException',原因:'[setValue:forUndefinedKey:]:此类不符合键值编码规范,无法为键名设置值。'

请帮我修复这个问题,谢谢。


在 Message 中创建一个变量名,它将解决这个问题。 - junaidsidhu
1个回答

3
问题在于您的“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
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接