我从我的 firebase 数据库中提取 userUID 数据并将其放入一个数组中。当我在 observe 闭包外部打印数组时,它不会打印,但在闭包内部会打印。这里发生了什么?
let databaseRef = Database.database().reference()
var userUIDArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
databaseRef.child("Users").observe(.value, with: { (snapshot) in
let snapshots = snapshot.children.allObjects as! [DataSnapshot]
for child in snapshots {
self.userUIDArray.append(child.key)
}
})
print(self.userUIDArray)
}
最佳答案
闭包内的代码是异步执行的(在发出网络请求之后),这意味着它在 viewDidLoad
内的其余代码之后执行。
以下是代码执行时间的快速排序:
override func viewDidLoad() {
// #1
databaseRef.child("Users").observe(.value, with: { (snapshot) in
// #3
})
// #2
}
闭包外的 print
语句不打印任何内容,因为调用它时数组中没有元素。闭包内的 print
语句起作用是因为数组在调用之前已被修改。
以下是从 Firebase 返回时如何使用此数据的示例:
let databaseRef = Database.database().reference()
var userUIDArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
databaseRef.child("Users").observe(.value, with: { (snapshot) in
let snapshots = snapshot.children.allObjects as! [DataSnapshot]
for child in snapshots {
self.userUIDArray.append(child.key)
}
updateUserInterface()
})
}
func updateUserInterface() {
// update the UI here using the `userUIDArray` variable
myTableView.reloadData()
}
关于arrays - 在闭包中附加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44991622/