使用GCD在Swift中的另一个函数之后调用函数

时间:2015-07-16 03:34:29

标签: swift grand-central-dispatch

我有一个功能A,它包含另外两个功能B& C.内部功能A一旦功能B完成,我需要调用功能C.我想我需要使用Grand Central Dispatch的dispatch_group_notify,但我不太清楚如何使用它。我在函数B&中调用异步方法。 C.这是我的职能:

func A() {

    func B() {

    // Three asynchronous functions

    }

    func C() {

    // More asynchronous functions that handle results from func B()

    }

    funcB()
    funcC()
}

编辑:在func B()中,我有三个异步功能需要一段时间才能完成。当我使用以下方法时,在func C()中的方法完全完成之前,仍然会调用func B()。在调用第二个调度组之前,如何确保它们完全完成?

func A() {

var group = dispatch_group_create()

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

            // async function 1
            // async function 2
            // async function 3
        }

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

           // async function

        })

}

1 个答案:

答案 0 :(得分:1)

以下是如何等待任务完成的示例:

func asyncTaskSimulation(delay: NSTimeInterval, completion: (NSTimeInterval) -> ()) {
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
    Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
      completion(delay)
  }
}

func A() {

  func B(completion: () -> ()) {

    print("Function B start")

    let group = dispatch_group_create()

    dispatch_group_enter(group)
    asyncTaskSimulation(1.0) { (delay) in
      print("First task after \(delay)s")
      dispatch_group_leave(group)
    }

    dispatch_group_enter(group)
    asyncTaskSimulation(2.0) { (delay) in
      print("Second task after \(delay)s")
      dispatch_group_leave(group)
    }

    dispatch_group_enter(group)
    asyncTaskSimulation(0.5) { (delay) in
      print("Third task after \(delay)s")
      dispatch_group_leave(group)
    }

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
    completion()

    print("Function B end")
  }

  func C() {
    print("Function C start")
    print("Whatever")
    print("Function C end")
  }

  B() {
    C()
  }

}

A()

这是输出:

Function B start
Second task after 0.5s
First task after 1.0s
Second task after 2.0s
Function C start
Whatever
Function C end
Function B end