現(xiàn)在在iOS8之后饥漫,提交到gcd隊(duì)列中的dispatch block也可取消了,只需要簡(jiǎn)單的調(diào)用dispatch_block_cancel傳入想要取消的block即可:
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);
dispatch_block_t block1 = dispatch_block_create(0, ^{
NSLog(@"block1 begin");
[NSThread sleepForTimeInterval:3];
NSLog(@"block1 end");
});
dispatch_block_t block2 = dispatch_block_create(0, ^{
NSLog(@"block2 ");
});
dispatch_async(queue, block1);
dispatch_async(queue, block2);
//取消執(zhí)行block2
dispatch_block_cancel(block2);
可以看到如下的執(zhí)行結(jié)果短荐,block2不再執(zhí)行了。
GCDTests[17271:902981] block1 begin
GCDTests[17271:902981] block1 end