从一个从firebase中检索数据的闭包获取数据 [英] getting data out of a closure that retrieves data from firebase
问题描述
我正在尝试从Firebase检索数据,并将数据存储在检索数据的闭包外部。
I am trying to retrieve data from Firebase and store that data outside of the closure that retrieves that data.
var stringNames = [String] ()
ref?.observeEventType(.Value, withBlock: { snapshot in
var newNames: [String] = []
for item in snapshot.children {
if let item = item as? FIRDataSnapshot {
let postDict = item.value as! [String: String]
newNames.append(postDict["name"]!)
}
}
stringNames = newNames
})
print(stringNames)
stringNames回来为空,但是当我从闭包中打印时,它有正确的数据。任何帮助将非常感谢,谢谢!
stringNames comes back empty, but when I print from inside the closure it has the correct data. Any help would be much appreciated, thank you!
推荐答案
这是因为当你从Firebase获取数据调用是异步。你可以做什么:
That's because when you fetch data from Firebase the call is Asynchronous. What you can do:
选项1 - 在闭包内设置你的逻辑(就像你在闭包内打印var一样)。
Option 1 - Set your logic inside the closure (Like what you have that print the var inside the closure).
选项2 - 定义自己的闭包,它将接收您的数据:
Option 2 - Define your own closure that going to receive your data like:
func myMethod(success:([String])->Void){
ref?.observeEventType(.Value, withBlock: { snapshot in
var newNames: [String] = []
for item in snapshot.children {
if let item = item as? FIRDataSnapshot {
let postDict = item.value as! [String: String]
newNames.append(postDict["name"]!)
}
}
success(newNames)
})
}
选项3 - 使用委托模式
Option 3 - Use the delegate pattern
protocol MyDelegate{
func didFetchData(data:[String])
}
class MyController : UIViewController, MyDelegate{
func myMethod(success:([String])->Void){
ref?.observeEventType(.Value, withBlock: { snapshot in
var newNames: [String] = []
for item in snapshot.children {
if let item = item as? FIRDataSnapshot {
let postDict = item.value as! [String: String]
newNames.append(postDict["name"]!)
}
}
self.didFetchData(newNames)
})
}
func didFetchData(data:[String]){
//Do what you want
}
}
这篇关于从一个从firebase中检索数据的闭包获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!