解析嵌套完成处理(parse nested completion handlers)

2019-09-29 23:13发布

我试图用一个完成处理程序在for循环中。 问题是,它会继续运行循环之前完成处理程序返回,因为它是一个异步调用。 附件是我的代码。 我是否需要使用GCD? 我是新的(显然)对SWIFT / IOS。 任何意见,将不胜感激。 短发

    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

Answer 1:

你可以使用DispatchGroups,这里是一个例子(摘自https://medium.com/@wilson.balderrama/how-to-use-dispatchgroup-gdc-with-swift-3-35455b9c27e7 。类似嵌套查询解析GCD但更新,以迅捷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
}


文章来源: parse nested completion handlers