解析嵌套的完成处理程序

编程入门 行业动态 更新时间:2024-10-28 06:35:47
本文介绍了解析嵌套的完成处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在for循环中使用完成处理程序.问题在于,由于这是异步调用,因此它将在完成处理程序返回之前继续运行循环.附件是我的代码.我需要使用GCD吗?我是新来的(显然)是swift/ios.任何建议将不胜感激.鲍勃

I am trying to use a completion handler in a for loop. The problem is that it will keep running the loop before the completion handler returns since it is an async call. Attached is my code. Do I need to use GCD? I am new (obviously)to swift/ios. Any advice would be much appreciated. Bob

for srcTerm in sFields { //search using all search fields multiQuery (searchTerm: srcTerm) { if srResult.count < self.lastValue { self.lastValue = srResult.count self.lastSearch = srcTerm } } // Do more stuff } func multiQuery (searchTerm: String, completion: @escaping ([PFObject]) -> ()) { var exArray = [PFObject] () let query = PFQuery(className: "searchLinks") do { query.whereKey("searchTerms", equalTo: searchTerm) query.findObjectsInBackground (block: { (objects, error)-> Void in if let error = error { print("Error Generated: ",error) return } if let objects = objects { // do stuff } completion(self.srResult) }) } } // end of function

推荐答案

您可以使用DispatchGroups,这是一个示例(摘自 medium/@wilson.balderrama/how-to-use-dispatchgroup-gdc-with-swift-3- 35455b9c27e7 .类似于具有嵌套解析查询的GCD ,但已更新为Swift 3 API):

You could use DispatchGroups, here's an example (taken from medium/@wilson.balderrama/how-to-use-dispatchgroup-gdc-with-swift-3-35455b9c27e7. Similar to GCD with nested Parse Queries but updated to Swift 3 API):

// Just a sample function to simulate async calls func run(after seconds: Int, closure: @escaping () -> Void) { let queue = DispatchQueue.global(qos: .background) queue.asyncAfter(deadline: .now() + .seconds(seconds)) { closure() } } let group = DispatchGroup() group.enter() run(after: 6) { print("Hello after 6 seconds") group.leave() } group.enter() run(after: 3) { print("Hello after 3 seconds") group.leave() } group.enter() run(after: 1) { print("Hello after 1 second") group.leave() } group.notify(queue: DispatchQueue.global(qos: .background)) { print("All async calls were run!") }

使用您的代码:

let group = DispatchGroup() for srcTerm in sFields { //search using all search fields group.enter() multiQuery (searchTerm: srcTerm) { if srResult.count < self.lastValue { self.lastValue = srResult.count self.lastSearch = srcTerm } group.leave() } } group.notify(queue: DispatchQueue.global(qos: .background)) { // Do something after all async calls are done }

更多推荐

解析嵌套的完成处理程序

本文发布于:2023-11-26 05:35:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632844.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!