gpt4 book ai didi

swift - 循环中的异步 DispatchQueue

转载 作者:行者123 更新时间:2023-11-30 12:36:52 25 4
gpt4 key购买 nike

So my goal here is to basically perform a query in a while loop and append results of the query to my array. When I run the code my "level" variable starts from zero and increments infinitely. I'm highly convinced that my problem is caused by fact that my code is running on 2 async queues but just can't figure out the exact cause.

func displayPathOf(参数:参数,threadTableView:UITableView){

    array.removeAll()
threadTableView.reloadData()
var level = argument.level!-1
array.insert(argument, at: 0)
var stop = false

DispatchQueue.global(qos: .userInteractive).async {

repeat {

level += 1
print(level)
let query = Argument.query()?.whereKey("level", equalTo: level).addDescendingOrder("reach")
query?.getFirstObjectInBackground(block: { (object, error) in

if object != nil {

DispatchQueue.main.async {
array.append(object as! Argument)
print(array)
threadTableView.reloadData()}

} else {

stop = true
print(error)

}
})
} while stop == false
}
}

最佳答案

您的代码归结为:

do-in-background {
repeat {
level += 1
do-in-background { ... }
} while stop == false
}

do-in-background(即asyncgetFirstObjectInBackground)立即返回,因此从这个循环的角度来看,它 block 中的内容并不重要。这相当于一个紧密循环,尽可能快地增加级别。

您似乎正在尝试序列化对 getFirstObjectInBackground 的调用。您可以通过以下两种方式之一执行此操作:

  • 让完成 block 自行启动下一个搜索并删除repeat循环。
  • 使用 DispatchGroup 等待完成 block 完成。

就您而言,我可能会推荐第一个。摆脱 stop 并使函数(模糊地)类似于:

func fetchObject(at level: Int) {
let query = Argument.query()?.whereKey("level", equalTo: level).addDescendingOrder("reach")
query?.getFirstObjectInBackground(block: { (object, error) in
if let object = object {
DispatchQueue.main.async {
array.append(object as! Argument)
print(array)
threadTableView.reloadData()}

// Schedule the next loop
DispatchQueue.global(qos: .userInteractive).async { fetchObject(level + 1) }

} else {
print(error)
}
})
}

关于swift - 循环中的异步 DispatchQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42755389/

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