更新Firebase时由于未捕获的异常'NSUnknownKeyException'而终止应用程序

时间:2019-07-07 23:27:09

标签: swift firebase firebase-realtime-database

在Firebase中创建用于添加键值对的函数时,出现以下报告,导致崩溃

  

*由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[valueForUndefinedKey:]:此类不符合键值编码的键值。   * 第一个调用堆栈:   (0x1dbd9a3a8 0x1daf9fd00 0x1dbcb36c8 0x1dc796054 0x1dc7ed2a0 0x1dc7070e0 0x102e58cc8 0x102e50640 0x102e4ed18 0x102e4f2c8 0x103f24214 0x103f13f84 0x1daf9b760 0x20906dbf0 0x208af1f94 0x208af22c8 0x208af12dc 0x2090a6a90 0x2090a7cc8 0x209086f50 0x209152150 0x20915490c 0x209154c7c 0x20914d9c4 0x1dbd2a444 0x1dbd2a3c0 0x1dbd29c7c 0x1dbd24950 0x1dbd24254 0x1ddf63d8c 0x20906c4c0 0x102f2befc 0x1db7e0fd8)   libc ++ abi.dylib:以类型为NSException的未捕获异常终止   调试器发出的消息:无法发送第k个数据包

我的数据库布局如下:enter image description here 我相信问题是我在函数中将其称为错误路径。

我更新“得分”的功能是:

func updateRecentScore(chatRoomId: String, score: Int) {

let date = dateFormatter().string(from: Date())

firebase.child(kRECENT).queryOrdered(byChild: kCHATROOMID).queryEqual(toValue: chatRoomId).observeSingleEvent(of: .value) { (snapshot) in

    if snapshot.exists() {
        for recent in ((snapshot.value as! NSDictionary).allValues as Array) {
            updateRecentScoreItem(recent: recent as! NSDictionary, score: score)
        }
    }

}



 }

func updateRecentScoreItem(recent: NSDictionary, score: Int) {

var score = recent[kSCORE] as! Int

let values = [kSCORE: score] as [String: Any]

firebase.child(kRECENT).child((recent[kRECENTID] as? String)!).updateChildValues(values as [NSObject : AnyObject]) {
    (error, ref) -> Void in

    if error != nil {
        ProgressHUD.showError("Couldnt update recent: \(error!.localizedDescription)")
    }
}

 }

我在此处调用该函数以对其进行更新:

let score = recentsRef.child(kRECENTID).value(forKey: kSCORE) as? Int

    let newScore = score! + 1

    let score1 = firebase.child(kRECENT).queryOrdered(byChild: kCHATROOMID).queryEqual(toValue: chatRoomId).value(forKey: kSCORE) as? Int

    let newScore1 = score1! + 1


    updateRecentScore(chatRoomId: chatRoomId, score: newScore1)

感谢所有帮助,因为我不确定如何解决此问题,因此我尝试到处寻找答案。如果您需要更多信息,请询问。

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找这个:

func updateRecentScore(chatRoomId: String, score: Int) {

  let date = dateFormatter().string(from: Date())

  firebase.child(kRECENT).queryOrdered(byChild: kCHATROOMID).queryEqual(toValue: chatRoomId).observeSingleEvent(of: .value) { (snapshot) in

    if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
        for child in snapshots {
          child.ref.child(kSCORE).setValue(score+1)
        }
    }
  }
}

主要区别:

  • 我使用内置的children属性遍历子节点,这意味着我得到了Snapshot,这使我可以简单地查找每个子节点的ref。 / li>
  • 我直接在score属性上致电setValue(),因为您只是在更新该属性。实际上,updateChildValues仅在您要一次性更新多个但并非全部属性时才有用。