2016-11-24 52 views
3

下面是代碼:火力地堡夫特3.0 setValuesForKeysWithDictionary

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 :]:這個類不是密鑰名稱的密鑰值編碼。「

請您好好幫我解決這個問題。

+0

在信息創建一個變量名。它會解決這個問題 – junaidsidhu

回答

2

問題是您的Message模型類與您試圖通過setValuesForKeys方法將其放入實例中的內容不匹配。你的字典不符合Message類。

這是錯誤消息告訴你的:你的應用試圖爲你的Message類中不存在的snapshot.value中的密鑰設置一個值。

檢查是完全存在的相同數量在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 
    } 

}