2016-11-24 16 views
3

ここではコードです:Firebaseスウィフト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メソッドを使用してインスタンスの内部に配置しようとしているものの間に不一致があるという問題があります。あなたの辞書はクラスと並んでいません。

これは、クラスに存在しないsnapshot.valueのキーの値を設定しようとしたときのエラーメッセージです。

のようにMessageクラスに同じ名前のという同じ番号のプロパティーがあることを確認してください。

不整合を回避するために、次のようなあなたの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 
    } 

} 
関連する問題