ios - 使用 UpdateChildValues 从 Firebase 中删除

标签 ios swift firebase firebase-realtime-database

我正在尝试同时从 Firebase 数据库中的多个位置删除数据。

Firebase docs状态:

"The simplest way to delete data is to call removeValue on a reference to the location of that data. You can also delete by specifying nil as the value for another write operation such as setValue or updateChildValues. You can use this technique with updateChildValues to delete multiple children in a single API call."

我的代码是

let childUpdates = [path1 : nil,
                    path2 : nil,
                    path3 : nil,
                    path4 : nil]

    ref.updateChildValues(childUpdates)

所有四个路径都是字符串,但我收到错误:

"Type of expression is ambiguous without more context."

我假设这是因为 nil 值而发生的,因为如果我用其他值(例如 Int)替换 nil ,错误就会消失。

使用 updateChildValues 从 Firebase 删除数据的正确方法是什么?我们希望它的工作方式与 Firebase 中的 removeValue() 函数类似。我们更愿意这样做的原因是因为它可以在一次调用中从多个位置删除。

最佳答案

所以这里的问题是

ref.updateChildValues(childUpdates)

需要一个 [String: AnyObject!] 参数来 updateChildValues 和 AnyObject!不能为 nil(即您不能使用 AnyObject?这是一个可能为 nil 的可选值)

但是,你可以这样做

let childUpdates = [path1 : NSNull(),
                    path2 : NSNull(),
                    path3 : NSNull(),
                    path4 : NSNull()]

因为任何对象!现在是一个 NSNull() 对象(不是 nil),并且 Firebase 知道 NSNull 是一个 nil 值。

编辑

您可以对此进行扩展以进行多位置更新。假设你有一个结构

items
   item_0
      item_name: "some item 0"
   item_1
      item_name: "some item 1"

并且您想要更新两个项目名称。这是快速代码。

func updateMultipleValues() {
    let path0 = "items/item_0/item_name"
    let path1 = "items/item_1/item_name"

    let childUpdates = [ path0: "Hello",
                         path1: "World"
    ]

    self.ref.updateChildValues(childUpdates) //self.ref points to my firebase
}

结果是

items
   item_0
      item_name: "Hello"
   item_1
      item_name: "World"

关于ios - 使用 UpdateChildValues 从 Firebase 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569908/

相关文章:

iphone - 如何根据平台定义相同的宏但具有不同的值?

ios - 图像及其属性列表

ios - 来自 Swift 代码的抗锯齿像素被 OpenCV 转换为不需要的黑色像素

ios - 打开/关闭 MIC 以进行 VOIP 通话

ios - Swift - NSFetchRequest 错误

swift - Firebase 配置失败 - Swift

ios - 无法与谷歌地图中的自定义信息窗口交互

ios - 将新用户插入 firebase

ios - 火力地堡, swift : `runTransactionBlock()` returns null

javascript - Firebase 用户验证电子邮件操作 URL 到自定义 URL