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

How to wait for completion handler to finish? Dispatch.group?

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

问题

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

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")
        }
    })
}

在此先感谢您的帮助!

您需要使用 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
}