等待异步功能完成使用GCD

时间:2015-10-10 06:00:08

标签: ios swift grand-central-dispatch

我有一个查询Parse的异步函数。我需要等到Parse查询中的所有对象都返回后再调用我的第二个函数。问题是,我正在使用:

          var group: dispatch_group_t = dispatch_group_create()

          dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in

                asyncFunctionA() // this includes an async Parse query

            }

          dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in

                asyncFunctionB() // must be called when asyncFunctionA() has finished

            }

...但是,在asyncFunctionB()中我的数组附加任何对象之前,asyncFunctionA()被调用。是不是使用GCD通知来观察先前函数的完成?为什么不在这里工作?

1 个答案:

答案 0 :(得分:1)

就像Parse使用完成块/闭包的概念一样,您需要在asyncFunctionA中执行相同操作:

func asyncFunctionA(completionHandler: () -> ()) {
    // your code to prepare the background request goes here, but the
    // key is that in the background task's closure, you add a call to
    // your `completionHandler` that we defined above, e.g.:

    gameScore.saveInBackgroundWithBlock { success, error in
        if (success) {
            // The object has been saved.
        } else {
            // There was a problem, check error.description
        }

        completionHandler()
    }
}

然后你可以做类似你的代码片段的事情:

let group = dispatch_group_create()

dispatch_group_enter(group)
asyncFunctionA() {
    dispatch_group_leave(group)
}

dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
    self.asyncFunctionB()
}

注意,如果函数A真的使用Parse的异步方法,那么就不需要在那里使用dispatch_async。但如果您出于某种原因需要它,请随时添加,但请确保{/ 1}} 之前发送到某个后台线程。

坦率地说,如果我将大量项目添加到该组中,我只会使用组。如果它真的只是B等待单打A,我就完全退出了这些小组并且只是这样做:

dispatch_group_enter