iOS 延迟的执行和取消

最近在项目中遇到了一个需要延迟执行的操作,出于习惯选择了GCD的dispatch_after这个函数。

但由于项目需要某个场景下取消这个处于等待执行中的action, 当时没有找到对应的方法,就换成了performSelector afterDelay 这种方案。

后来查询了一些资料,自己整理了一下iOS中的三种延迟和取消执行的方法。


1、NSTimer

NSTimer 是iOS开发工作中经常会使用到,充当着定时器的作用。NSTimer不会阻塞主线程,只是把action滞后,到指定时间由主线程继续执行。

  • 执行NSTimer
self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(prtintHellowWorld:) userInfo:@{@"words":@"hello world"} repeats:NO];
  • 取消NSTimer
[self.timer invalidate];

//取消延迟执行只需要调用 invalidate 方法即可


2、performSelector…withObject…afterDelay

该方法也是在主线程中执行的方法,同NSTimer一样,不会阻塞主线程。

  • 执行performSelector
[self performSelector:@selector(recordAotoStop:) withObject:@"stopRecord" afterDelay:3.0];
  • 取消performSelector
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(recordAotoStop:) object:@"stopRecord"];

//这里注意,cancel的参数要和执行action的时候传递的参数保持一致。这种方法用来取消某个特定的延迟方法。

  • 下面这个是取消performSelector的所有被延迟执行的方法:
[NSObject cancelPreviousPerformRequestsWithTarget:self];

3、GCD

GCD的dispatch_after方法常被用来做延迟执行,与上面的两个相比,它可以在除了主线程之外的线程执行,当然也不会阻塞线程。

  • 执行 dispatch_after
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    [self prtintMyWords:@"hello world"];
});
  • 取消 dispatch_after
GCD的dispatch_after方法并没有直接的cancel方案,需要我们自己去构造一个取消。 

具体实现参考github上的这个开源库。


你可能感兴趣的:(iOS 延迟的执行和取消)