var ergebnisBluetezeit = Set<String>()
let refBluetezeit = rootRef.child("Pflanzen").child("Eigenschaften").child("Blütezeit")
refBluetezeit.child("Februar").observeSingleEvent(of: .value, with: { snapshot in
for plant in snapshot.children {
self.ergebnisBluetezeit.insert((plant as AnyObject).value)
}
})
print(ergebnisBluetezeit)
我想从我的 Firebase 数据库检索数据。检索过程确实可以工作,但以下内容让我感到困惑:打印的当前输出是一个空集,但是当我在其他地方使用 var ergebnisBluetezeit 时(例如设置一个按钮,哪个操作是打印 ergebnisBluetezeit),它被填充。当我将打印放入 for 循环中时,它也打印出正确的输出。 我似乎不明白这里的控制流程,所以我的问题: 我如何使用当前打印语句所在的集合? 感谢您的帮助。
最佳答案
这是异步调用的逻辑
print("1") // empty
refBluetezeit.child("Februar").observeSingleEvent(of: .value, with: { snapshot in
print("3") // empty
for plant in snapshot.children {
self.ergebnisBluetezeit.insert((plant as AnyObject).value)
}
print(ergebnisBluetezeit) // not empty
})
print("2") // empty
无论您在代码顺序中的哪个位置运行 print ,在请求完成之前该值都是空的,如上面的编号顺序 1 , 2 , 3 要知道它何时完成,您可以使用类似的补全
func getData(completion:@escaping() -> ()) {
let refBluetezeit = rootRef.child("Pflanzen").child("Eigenschaften").child("Blütezeit")
refBluetezeit.child("Februar").observeSingleEvent(of: .value, with: { snapshot in
for plant in snapshot.children {
self.ergebnisBluetezeit.insert((plant as AnyObject).value)
}
completion()
})
}
然后打电话
getData {
print(ergebnisBluetezeit)
}
关于ios - 从 Firebase 检索信息时控制流如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890317/