2015-09-07 78 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]