为什么 Dispatch Group Notify 会被调用两次?

Why Dispatch Group Notify get's called twice?

我正在尝试让我的应用程序使用调度组来确保所有邀请都已发送,然后再继续。我认为 notify 回调仅在所有 enters 具有匹配的 leave 时被调用,但我的似乎被多次调用,这是我的代码:

    for invite in invites {
        dispatchGroup.enter()
        let ref = FIRDatabase.database().reference().child("users").child(invite.id).child("invites")
        print(invite)
        ref.updateChildValues([name: nameTextField.text!]) { (error, ref) -> Void in
            dispatchGroup.leave()

            dispatchGroup.notify(queue: DispatchQueue.main, execute: {
                print("YOYOYO")
            })
        }
    }

在我的控制台中,我看到了 2 个 "YOYOYO",这让我很困惑。如果我做错了或者我的假设有误,有人可以告诉我吗?

你可能有两个 invites。如果您想在所有 invites 处理完毕后收到通知,请将 dispatchGroup.notify 移出 for 循环:

for invite in invites {
    dispatchGroup.enter()
    let ref = FIRDatabase.database().reference().child("users").child(invite.id).child("invites")
    print(invite)
    ref.updateChildValues([name: nameTextField.text!]) { (error, ref) -> Void in
        dispatchGroup.leave()            
    }
}

dispatchGroup.notify(queue: DispatchQueue.main) {
    print("YOYOYO")
}