gpt4 book ai didi

ios - 如何使用 DispatchGroup 在 for 循环中进行异步调用

转载 作者:可可西里 更新时间:2023-11-01 00:58:02 25 4
gpt4 key购买 nike

在下面的示例代码中,我在失败时调用了 complete(false)。但是,由于我使用 DispatchGroup 对象来确保所有异步请求都已完成,所以我不能在失败时调用 syncGroup.leave(),因为 notify 将被调用,其中包含 complete(true),使此函数返回 true,而它应该返回 false失败。

我在未能正确完成我的功能时没有调用 syncGroup.leave() 是否正确?或者我应该调用 syncGroup.leave() 并以某种方式尝试确定结果是什么,以便在失败时返回 false

let syncGroup = DispatchGroup()
syncGroup.enter()
for track in unsynced {
register(time: time, withCompletion: { (success: Bool) -> () in

if success {
self.debug.log(tag: "SyncController", content: "Registered")
syncGroup.leave()
}
else {
complete(false)
}
})
}

//all requests complete
syncGroup.notify(queue: .main) {
self.debug.log(tag: "SyncController", content: "Finished registering")
complete(true)
}

最佳答案

您必须在 for 循环中输入组。您可能想要引入一个额外的错误标志。

示例实现:

    var fail = false
let syncGroup = DispatchGroup()

for track in unsynced {
syncGroup.enter()
register(time: time, withCompletion: { (success: Bool) -> () in

if success {
self.debug.log(tag: "SyncController", content: "Registered")
syncGroup.leave()
}
else {
fail = true
syncGroup.leave()
}
})
}

//all requests complete
syncGroup.notify(queue: .main) {
if fail {
complete(false)

} else {
self.debug.log(tag: "SyncController", content: "Finished registering")
complete(true)
}
}

关于ios - 如何使用 DispatchGroup 在 for 循环中进行异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40652869/

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