问题描述
我正在尝试在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,这是一个示例(摘自 https://medium.com/@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 https://medium.com/@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
}
这篇关于解析嵌套的完成处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!