可变范围不是我想要的吗?

时间:2019-03-02 21:40:32

标签: ios swift firebase firebase-realtime-database

我有一个名为retrieveUsers()的函数,该函数在一个函数中调用,该函数可提取Post节点下的所有帖子。

在下面的代码中,我将当前的UID保存到具有全局作用域的变量中。但是每次调用此函数时,变量(lastUID)似乎都会被重置。即使此方法本质上是在for循环中调用的。

 func retrieveUsers(value: Post) {
    print(lastUID, "-=-=--=-=")
    print(value.user.userID != lastUID, ": ", value.user.userID!, " email left old ... one -> ", lastUID)

    if value.user.userID != lastUID {//Ignore this line
        let ref = Database.database().reference()
        if value.user.userID != nil {
            let UID = value.user.userID!
            print(UID, "Thoi s is the uid in the users fetch fx")
            ref.child("users2").child(UID).observe(.value, with: { (snapshot) in
                let email = "\(snapshot.childSnapshot(forPath: "email").value as! String)"
                do {
                    value.user.email = email
                    //even with the two values being in here the same thing happens
                }
                self.lastUID = UID
                self.lastEmail = email
            })
        }
    } else {
        print("ESC this is the same user")
        value.user.email = lastEmail
    }
}

出了什么问题?

1 个答案:

答案 0 :(得分:1)

  

即使本质上是在for循环中调用此方法,也是如此。

在for-循环的每个循环中,全局var都会更改,并且由于对firebase的调用是异步的,因此您无法使用对应的UID来捕获每个抓取操作

您需要创建一个模型,并在其中使用属性作为uid进行这些调用