问题描述
我正在尝试同时从 Firebase 数据库中的多个位置删除数据.
I am trying to delete data from several locations in the Firebase database simultaneously.
Firebase 文档 状态:
"删除数据的最简单方法是在对该数据位置的引用上调用 removeValue.您也可以通过将 nil 指定为另一个写入操作(例如 setValue 或 updateChildValues)的值来删除.您可以将此技术用于updateChildValues 以在单个 API 调用中删除多个子项."
我的代码是
let childUpdates = [path1 : nil,
path2 : nil,
path3 : nil,
path4 : nil]
ref.updateChildValues(childUpdates)
所有四个路径都是字符串,但出现错误:
All four paths are strings, but I get an error:
没有更多上下文的表达类型是不明确的."
我认为这是因为 nil 值而发生的,因为如果我用其他任何东西(例如 Int)替换 nil,错误就会消失.
I'd assume this occurs because of the nil values, since if I replace nil with anything else (such as an Int) the error disappears.
使用 updateChildValues 从 Firebase 删除数据的正确方法是什么?我们希望它以类似于 Firebase 中的 removeValue() 函数的方式工作.我们更愿意这样做的原因是因为它可以在一次调用中从多个地方删除.
What is the correct way to use updateChildValues to delete data from Firebase? We want it to work in a similar way to the removeValue() function in Firebase. The reason we would prefer to do this is because it can remove from multiple places in one call.
推荐答案
所以这里的问题是
ref.updateChildValues(childUpdates)
需要一个[String: AnyObject!] 参数来更新ChildValues 和AnyObject!不能是 nil(即你不能使用 AnyObject?这是一个可以是 nil 的可选)
requires a [String: AnyObject!] parameter to updateChildValues, and AnyObject! cannot be a nil (i.e. you can't use AnyObject? which is an optional that could be nil)
但是,您可以这样做
let childUpdates = [path1 : NSNull(),
path2 : NSNull(),
path3 : NSNull(),
path4 : NSNull()]
因为 AnyObject!现在是一个 NSNull() 对象(不是 nil),并且 Firebase 知道 NSNull 是一个 nil 值.
Because AnyObject! is now an NSNull() object (not nil), and Firebase knows that NSNull is a nil value.
编辑
您可以对此进行扩展以进行多位置更新.假设你有一个结构
You can expand on this to also do multi-location updates. Suppose you have a structure
items
item_0
item_name: "some item 0"
item_1
item_name: "some item 1"
并且您想要更新两个项目名称.这是快速代码.
and you want update both item names. Here's the swift code.
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"
这篇关于使用 UpdateChildValues 从 Firebase 中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!