为什么要在这段代码之前执行此循环?

时间:2019-07-31 10:59:14

标签: ios swift firebase firebase-realtime-database

为什么即使在firebase代码之后键入for循环,也要在firebase代码之前执行for循环?

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)
}  

1 个答案:

答案 0 :(得分:1)

这是因为firebase observe事件是asynchronous,因此,如果要在此之后执行代码,则需要将其移入块中。

所以您的代码将是:

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时,请不要忘记remove观察。