iOS里延迟的执行和取消

参考链接

https://blog.csdn.net/u013749108/article/details/51092814


1、NSTimer

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

执行NSTimer

self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(prtintMyWords:) userInfo:@{@"words":@"hello world"} repeats:NO];

取消NSTimer

[self.timer invalidate];//取消延迟执行只需要调用 invalidate 方法即可

2、performSelector…withObject…afterDelay

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

执行performSelector

[self performSelector:@selector(controlHeadViewShowType:) withObject:ShowTypeHidenAlways afterDelay:3];2

取消performSelector

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(controlHeadViewShowType:) object:ShowTypeHidenAlways];

这里注意,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上的这个开源库。 

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容