【问题标题】:Why does this loop execute before this piece of code?为什么这个循环在这段代码之前执行?
【发布时间】:2019-07-31 10:59:14
【问题描述】:

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

【问题讨论】:

  • 因为observe 异步工作。
  • 先阅读here。然后观察异步工作,所以如果你想在观察之后执行循环,你需要将它添加到块中。
  • @Kerberos 谢谢!抱歉,我对 iOS 开发真的很陌生。如何将循环添加到块中以便在之后执行?
  • @VishaalKumar 我添加了一个答案,因为它不适合评论。

标签: ios swift firebase firebase-realtime-database


【解决方案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 观察。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 2013-07-25
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多