gpt4 book ai didi

swift - 使用 DispatchGroup 在 for-in 循环中处理异步回调仅在所有循环都成功时有效

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:40 27 4
gpt4 key购买 nike

下面的代码是任务的粗略草图。查询数据库,它返回一个结果集合,该集合循环搜索特定属性,如果找到该属性,则立即查询文件存储,其异步完成处理程序返回循环中的文件。因为我在 for-in 循环内处理异步回调,所以我使用 DispatchGroup 来管理它。仅当集合中的所有文档都具有 someIdentifier 属性时,此设置才有效。如果集合中的一个文档没有该属性,调度组永远不会调用 notify(),我们就会陷入困境。

someDatabaseQuery.retrieveSomeData { (data, error) in

guard let data = data, error == nil else {
return
}

// database has retrieved data, create dispatch group
let dispatchGroup = DispatchGroup()

for document in data { // loop through collection

// check if document has some identifier
guard let someIdentifier = document["someIdentifier"] as? String else {
return
}

dispatchGroup.enter() // identifier found, enter dispatch

// perform async operation inside loop
Filestorage.getSomeFile(forURL: someIdentifier) { (data, error) in

guard let file = data, error == nil else {
return
}

// download the file
dispatchGroup.leave() // leave dispatch

}

}

dispatchGroup.notify(queue: .main) {

// all data grabbed, load table

}

}

最佳答案

如果调用 enter,则必须调用 leave。但是 getSomeFile 完成 block 中的 guard 可以阻止对 leave 的调用,即使您调用了 enter

一种解决方案是在完成 block 内使用defer。在 defer 中调用 leave 以确保无论您如何离开 block 都会调用它。

关于swift - 使用 DispatchGroup 在 for-in 循环中处理异步回调仅在所有循环都成功时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53423240/

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