【问题标题】:Variable scope not what I want it to be? [duplicate]变量范围不是我想要的? [复制]
【发布时间】:2019-03-02 21:40:31
【问题描述】:

我有一个名为 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
    }
}

出了什么问题?

【问题讨论】:

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

即使这个方法本质上是在 for 循环中调用的。

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

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

【讨论】:

  • 所以你是说只有在闭包内或者保存到可以存储该值的对象中才能存在该值?因此,尽管它被保存到全局变量中,但由于某种原因,代码不会保留 i 存储的值?
  • yes ,,,,,, for 循环会在您的响应从 firebase 返回之前覆盖该值
猜你喜欢
  • 1970-01-01
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 2011-04-21
  • 2015-08-21
  • 1970-01-01
  • 2013-11-29
相关资源
最近更新 更多