【问题标题】:Firebase Swift 3.0 setValuesForKeysWithDictionaryFirebase Swift 3.0 setValuesForKeysWithDictionary
【发布时间】:2016-11-24 13:24:23
【问题描述】:

代码如下:

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 中创建一个变量名。它将解决问题

标签: swift firebase firebase-realtime-database


【解决方案1】:

问题是您的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
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多