【问题标题】:Firebase Realtime database Element is unexpectedly nil (Swift)Firebase 实时数据库元素意外为零(Swift)
【发布时间】:2020-12-16 21:55:35
【问题描述】:

如果这是重复,请告诉我,我见过很多类似的问题。我遇到了一个问题,我能够在调用 RunTransactionBlock 和 ObserveSingleEvent 的过程中检索数据库中的大部分数据,但是当我尝试检索嵌套数据时,它给了我一个 nil 值。

我知道措辞有点不清楚,但这里有一个确切发生的例子:

这是当前的状态 my database

这是我的一段代码(newGame 是对动态创建的 Games 元素的引用):

global.newGame.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
        if var state = currentData.value as? [String : AnyObject] {
            var player0Info = state["player0Info"] as? [String : AnyObject]
            var hand = player0Info?["Hand"] as? Array<String> 
            var name = player0Info?["Name"] as? String
            var playerNum = player0Info?["PlayerNum"] as? Int
            var score = player0Info?["Score"] as? Int
            var thingToGet = player0Info?["ThingToGet"] as? [String : AnyObject]
            print(hand!)
            print(name!)
            print(playerNum!)
            print(score!)
            print(thingToGet)
            //Code to modify data
            //...
            currentData.value = state
        }
      return TransactionResult.success(withValue: currentData)
    }) { (error, committed, snapshot) in
      if let error = error {
        print(error.localizedDescription)
      }
    }

这给了我一个输出

["card1", "card2", "card3"]
Jeff
0
0
nil

为什么在这种情况下我无法访问 ThingToGet?当我使用 ObserveSingleEvent 而不是事务时,也会发生同样的事情,即使数据清楚地存在于数据库中,我似乎也无法做任何事情让它不显示为 nil。

旁注:我知道我不应该在 firebase 中使用数组,我正在努力摆脱它。

更新:我遗漏了一段导致问题的代码。如果组件尚不存在,为了添加组件,我有这段代码

if thingToGet == nil {
    thingToGet = ["0": ["sampleInfo"]] as [String : AnyObject]
}
player0Info["ThingToGet"] = thingToGet as AnyObject
state["Player0Info"] = player0Info as AnyObject
CurrentData.value = state

这就是导致我的问题的原因。一切都正确写入数据库,但由于某种原因,当 ThingToGet 不是 nil 时执行它时,它总是给我一个 nil 值。为什么会这样?

【问题讨论】:

    标签: firebase firebase-realtime-database


    【解决方案1】:

    问题解决了!如果有比这更好的解决方案,请有人纠正我,但这是我为使其正常工作所做的工作。

    我变了

    var thingToGet = player0Info?["ThingToGet"] as? [String : AnyObject]      
    

    var thingToGet = player0Info?["ThingToGet"]
    

    我变了

    thingToGet = ["0": ["sampleInfo"]] as [String : AnyObject]
    

    thingToGet = ["0": ["sampleInfo"]] as [String : AnyObject] as AnyObject
    

    现在一切都按预期进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多