我正在尝试从 Firebase 检索数据并将该数据存储在检索该数据的闭包之外。
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 返回为空,但是当我从闭包内部打印时它有正确的数据。任何帮助将不胜感激,谢谢!
最佳答案
那是因为当您从 Firebase 获取数据时,调用是异步的。你可以做什么:
选项 1 - 在闭包内设置您的逻辑(就像您在闭包内打印 var 一样)。
选项 2 - 定义您自己的闭包来接收您的数据,例如:
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 - 使用委托(delegate)模式
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
}
}
关于ios - 从从 firebase 检索数据的闭包中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38364288/