Reputation: 1611
I know dispatch_async can handle thread.
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
});
});
But How can I cancel it the thread?
For example:
I have two viewcontrollers- AViewController and BViewController, A->present B, and a button to dismiss B.
I'll do myMethod
in BViewController, the things is I want to dismiss B when exec myMethod
, so I use dispatch_async
, it did dismiss from B to A. but after going back to AViewController, here comes the audio.
How can I stop the myMethod
after dismiss method exec immediately?
- (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
});
});
}
Upvotes: 1
Views: 132
Reputation: 17612
What you need for this is not GCD and dispatch_async
, but an NSOperation
. It is a high-level wrapper around GCD that allows you to have references to your async operations, check their status, cancel them, etc.
I recommend using a very handy subclass named NSBlockOperation
. You should keep a reference to your operation in your class, and if you need to cancel it, just call [self.myOperation cancel]
.
Upvotes: 2