gpt4 book ai didi

ios - 为什么这个循环在这段代码之前执行?

转载 作者:行者123 更新时间:2023-11-28 05:39:36 25 4
gpt4 key购买 nike

为什么 for 循环在 firebase 代码之前执行,即使它是在 firebase 代码之后输入的?

messageDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String,String>
print("Snapshot value \(snapshotValue)")
let email = snapshotValue["UserEmail"]!
if (email == Auth.auth().currentUser?.email as String?){
let user : UserString = UserString()
user.name = snapshotValue["UserName"]!
user.height = snapshotValue["UserHeight"]!
user.weight = snapshotValue["UserWeight"]!
user.date = snapshotValue["EntryDate"]!
userArray.append(user)
}
}

for index in 0...4{
print(index)
}

最佳答案

这是因为 firebase observe 事件是 asynchronous , 所以如果你想在这之后执行一段代码,你需要把它移到 block 中。

所以你的代码将是:

messageDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String,String>
print("Snapshot value \(snapshotValue)")
let email = snapshotValue["UserEmail"]!
if (email == Auth.auth().currentUser?.email as String?){
let user : UserString = UserString()
user.name = snapshotValue["UserName"]!
user.height = snapshotValue["UserHeight"]!
user.weight = snapshotValue["UserWeight"]!
user.date = snapshotValue["EntryDate"]!
userArray.append(user)
}
for index in 0...4{
print(index)
}
// self.afterBlock()
}

// func afterBlock() { yourCodeHere }

或者像在注释代码中那样在单独的方法中调用它。

别忘了remove当您关闭 ViewController 时观察。

关于ios - 为什么这个循环在这段代码之前执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com