ios - 为什么这个循环在这段代码之前执行?
问题描述
为什么 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)
}
解决方案
这是因为 firebaseobserve
事件是异步的,所以如果你想在这之后执行代码,你需要将它移动到块中。
所以你的代码将是:
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 }
或者在注释代码中使用单独的方法调用它。
关闭 ViewController 时不要忘记删除观察。
推荐阅读
- node.js - 如何使用 axios 使用 NodeJs 将数据发布到 Slack?
- r - R Shiny中的rHighchart
- javascript - 基本算术练习反应迟钝
- codeigniter - Codeigniter Google Recaptcha 表单验证在服务器中不起作用
- for-loop - 为什么我们在 for 循环中放了花括号?
- python - 找不到文件制造商数据源名称,并且未指定默认驱动程序 - pythonanywhere
- javascript - 输入元素内的动态数字操作,增量加法
- php - 无法在 localhost 中使用 guzzle 或 curl
- plesk - 在 Plesk 中将自定义用户代理添加到 Modsecurity OWASP 规则
- javascript - Javascript 切换样式显示 ON/OFF 在单个函数中不起作用?