首页 > 解决方案 > 为什么这个循环在这段代码之前执行?

问题描述

为什么 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)
}  

标签: iosswiftfirebasefirebase-realtime-database

解决方案


这是因为 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 时不要忘记删除观察。


推荐阅读