gpt4 book ai didi

swift - 为什么变量在循环内的解析查询中使用时不会改变它的值

转载 作者:行者123 更新时间:2023-11-30 12:37:53 24 4
gpt4 key购买 nike

My problem is as follows: I have an argument class where all arguments have a parentId which are indeed objectId of other arguments. I would like to write a query where I can get a list of all arguments that are connected to each other with this kind of parent-child relationship. So i have tried this..

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

}

but the problem is temporaryId inside the loop does not update itself. It remains the same in all iterartions. Hence when i do print(self.all) i simply get an array of 3 strings which all are parent of my initial argument

My goal is to get an array that is [parent of my initial argument, parent of parent of my initial argument, parent of parent of parent of my ...]

I have searched similar topics but couldn't find a solution. Any help would be very appreciated.

最佳答案

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

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

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 方面的练习还不够,所以如果我犯了一些语法错误,我很抱歉。

关于swift - 为什么变量在循环内的解析查询中使用时不会改变它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42628600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com