【问题标题】:Why variable doesn't change it's value when used in a Parse query inside a loop为什么变量在循环内的 Parse 查询中使用时不会改变它的值
【发布时间】:2017-03-06 14:50:15
【问题描述】:

我的问题如下:我有一个参数类,其中所有参数都有一个 parentId,它确实是其他参数的 objectId。我想写一个查询,我可以在其中获取通过这种父子关系相互连接的所有参数的列表。所以我试过这个..

class ArgumentViewController: UIViewController {

var all = [String]()
var temporaryId = "vEKV1xCO09"

override func viewDidLoad() {
    super.viewDidLoad()
    
    for _ in 1...3 {
        let query = PFQuery(className: "Argument").whereKey("objectId", equalTo: temporaryId)
        
        query.findObjectsInBackground { (objects, error) in
            if let arguments = objects {
                for argument in arguments {
                    self.all.append(argument["parentId"] as! String)
                    print(self.all)
                    self.temporaryId = argument["parentId"] as! String
                }
            }
        }
    }

}

但问题是循环内的temporaryId不会自行更新。它在所有迭代中保持不变。因此,当我执行 print(self.all) 时,我只需得到一个由 3 个字符串组成的数组,它们都是我的初始参数的父项

我的目标是得到一个数组,它是 [我的初始参数的父级,我的初始参数的父级的父级,我的父级的父级的父级...]

我搜索了类似的主题,但找不到解决方案。任何帮助将不胜感激。

【问题讨论】:

  • 所以你的问题是 self.temporaryId = argument["parentId"] as!字符串不会从“vEKV1xCO09”变为其他内容,对吗?
  • 完全正确
  • 我找到了原因,但仍然找不到解决方案。显然,由于“findObjectsInBackground”是一个异步查询,因此主线程在查询得出结论之前运行。我尝试使用“findObjects”而不是“findObjectsInBackground”,它为我提供了我正在寻找的数组,但显着减慢了 UI,给我一个“正在主线程上执行长时间运行的操作”警告。

标签: swift xcode parse-platform


【解决方案1】:

由于query.findObjectsInBackground 在后台线程中运行,因此无法在每个for 循环中使用新检索到的@"parentId" 更新temporaryId

所以我猜你可以创建一个递归函数,比如:

func getParentId() {
    let query = PFQuery(className: "Argument").whereKey("objectId", equalTo: temporaryId)

    query.findObjectsInBackground { (objects, error) in
        if let arguments = objects {
            for argument in arguments {
                self.all.append(argument["parentId"] as! String)
                print(self.all)
                self.temporaryId = argument["parentId"] as! String
                while (all.count <= 3) {
                    getParentId()
                }
            }
        }
    }
}

因为我是一名 Objective-C 开发人员,所以我没有在 Swift 上做足够的练习,所以如果我犯了一些语法错误,我很抱歉。

【讨论】:

    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多