2015-09-07 84 views
1

我知道dispatch_async可以處理線程。dispatch_async句柄事件

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // handle things that takes a long time 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     // update UI 
    }); 
}); 

但是我怎樣才能取消它的線程?

例如:

我有兩個viewcontrollers- AViewController和BViewController,A-> B存在,並且按鈕關閉B.

我會做BViewController myMethod,這個事情是我想要的解僱B當執行myMethod,所以我使用dispatch_async,它確實解僱了B到A,但回到AViewController後,這裏是音頻。

立即解除方法exec後,如何停止myMethod

- (void)myMethod { 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     // handles thing A 
     // play a audio 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      // update UI 
     }); 
    }); 
} 
+0

可能重複[如何停止使用dispatch \ _async創建的線程](http://stackoverflow.com/questions/17671828/how-to-stop-a-thread-created-with-dispatch-async) –

回答

2

你需要的是什麼是不是GCD和dispatch_async,而是一個NSOperation。它是GCD的一個高級包裝,允許您引用異步操作,檢查它們的狀態,取消它們等。

我推薦使用一個非常方便的子類NSBlockOperation。您應該在課堂中提及您的操作,如果您需要取消,請致電[self.myOperation cancel]