一替裆、dispatch_after
使用dispatch_after還有一個(gè)問(wèn)題就是取消問(wèn)題,當(dāng)然通常遇到了這種問(wèn)題大部分答案就是使用下面的方式:
[self performSelector:@selector(myDelayedMethod) withObject: self afterDelay: desiredDelay];
[NSObject cancelPreviousPerformRequestsWithTarget: self selector:@selector(myDelayedMethod) object: self];
不過(guò)如果你使用的是iOS 8及其以上的版本始绍,那么其實(shí)是可以取消的(如下)胜茧,當(dāng)然如果你還在支持iOS 8以下的版本不妨試試這個(gè)自定義的dispatch_cancelable_block_t類:
dispatch_block_t block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, ^{
NSLog(@"dispatch_after...");
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3*NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);
// 取消
dispatch_block_cancel(block);