如何等待完成处理程序完成? Dispatch.group?

时间:2017-07-16 19:54:51

标签: swift dispatch-async

我需要帮助改变我的代码,以便在循环之前等待完成处理程序。

问题

我正在尝试运行以下代码块:

let sourceCodes:[String] = self.makeCodeArray(codeString: (self.sourceDict?["Code"]!)!)

print("A")
for i in 0..<sourceCodes.count
{
    print("B")
    getRealtimeData(stopCode: sourceCodes[i], completion:
    {
        (realtimeSourceResult) in

        print("C")
        self.overallSourceResult.append(realtimeSourceResult)

        if i == sourceCodes.count - 1
        {
            print("D")
        }
        else
        {
            print("K")
        }
    })
}

以便输出为:

A
B
C
K
B
C
K
B
C    (BCK repeating until the last iteration)
K
...
B
C
D

但是,目前代码按以下顺序执行: A B B B B ... C K C K C K C D

如何更改代码以便以所需方式执行?我曾尝试过使用Dispatch.group,但我似乎无法使用它。

这是我尝试使用Dispatch.group

的解决方案
let sourceCodes:[String] = self.makeCodeArray(codeString: (self.sourceDict?["Code"]!)!)
let group = DispatchGroup()

print("A")
for i in 0..<sourceCodes.count
{
    group.enter()

    print("B")
    getRealtimeData(stopCode: sourceCodes[i], completion:
    {
        (realtimeSourceResult) in

        print("C")
        self.overallSourceResult.append(realtimeSourceResult)

        if i == sourceCodes.count - 1
        {
            print("D")
        }
        else
        {
            group.leave()
            print("K")
        }
    })
}

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您需要使用group.wait()。而且你需要移动你的group.leave()以便随时调用它。必须为每个leave调用enter,否则wait永远不会停止等待。

print("A")
for i in 0..<sourceCodes.count
{
    group.enter()

    print("B")
    getRealtimeData(stopCode: sourceCodes[i], completion:
    {
        (realtimeSourceResult) in

        print("C")
        self.overallSourceResult.append(realtimeSourceResult)

        if i == sourceCodes.count - 1
        {
            print("D")
        }
        else
        {
            print("K")
        }

        group.leave() // always call this
    })

    group.wait() // don't iterate until the completion handler is done
}