swift:异步任务+完成

use*_*552 5 ios dispatch-async swift swift2

我对swift中的异步任务感到非常困惑.我想做的是这样的......

 func buttonPressed(button: UIButton) {
   // display an "animation" tell the user that it is calculating (do not want to freeze the screen
   // do some calculations (take very long time) at the background
   // the calculations result are needed to update the UI
 }
Run Code Online (Sandbox Code Playgroud)

我试着这样做:

func buttonPressed(button: UIButton) {
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(queue) { () -> Void in
       // display the animation of "updating"
       // do the math here
        dispatch_async(dispatch_get_main_queue(), {
          // update the UI
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我发现UI已更新,无需等待我的计算完成.我对使用异步队列很困惑.有人帮吗?谢谢.

vad*_*ian 8

您需要一个具有异步完成处理程序的函数.

在计算结束时调用 completion()

func doLongCalculation(completion: () -> ())
{
  // do something which takes a long time
  completion()
}
Run Code Online (Sandbox Code Playgroud)

buttonPressed函数中调度后台线程上的calculate函数,并在完成后返回主线程以更新UI

func buttonPressed(button: UIButton) {
  // display the animation of "updating"
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {  
    self.doLongCalculation {
      dispatch_async(dispatch_get_main_queue()) {
        // update the UI
        print("completed")
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)