且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将完成处理程序汇集在一起​​,以便一旦执行多个闭包,方法就完成

更新时间:2023-11-20 23:14:22

仅需了解OOPer所说的内容,您正在寻找DispatchGroup.在下面,对taskAtaskBtaskC的调用是伪代码,但其他所有内容都是真实的:

Just to pick up on what OOPer said, you are looking for DispatchGroup. In the following, the calls to taskA, taskB, and taskC are pseudo-code, but everything else is real:

func doTasks(with object: Object, completionHandler: () -> Void) {
    let group = DispatchGroup()
    group.enter()
    taskA() {
        // completion handler
        group.leave()
    }
    group.enter()
    taskB() {
        // completion handler
        group.leave()
    }
    group.enter()
    taskC() {
        // completion handler
        group.leave()
    }
    group.notify(queue: DispatchQueue.main) {
        // this won't happen until all three tasks have finished their completion handlers
        completionHandler()
    }
}

每个enter在异步完成处理程序的末尾都由leave进行匹配,只有当所有匹配项都已实际执行后,我们才进入notify完成处理程序.

Every enter is matched by a leave at the end of the asynchronous completion handler, and only when all the matches have actually executed do we proceed to the notify completion handler.