Firebase Swift 3.0 setValuesForKeysWithDictionary

时间:2016-11-24 13:24:23

标签: swift firebase firebase-realtime-database

以下是代码:

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)

}

运行时,它会像这样崩溃:

  

由于未捕获的异常而终止应用程序&#39; NSUnknownKeyException&#39;,原因:&#39; [setValue:forUndefinedKey:]:此类不是密钥值的密钥值编码。&#39; < / p>

请帮我解决这个问题。

1 个答案:

答案 0 :(得分: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
    }

}