GCD中使用dispatch_after函数延迟处理任务 iOS

在实际的开发中,经常会遇到想要在指定的时间间隔后执行某个处理

<一>在GCD中提供了dispatch_after函数来完成这一操作

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        <#code to be executed after a specified delay#>

    });

其中(int64_t)(<#delayInSeconds#> * NSEC_PER_SEC) 返回的是时间间隔,数值与 NSEC_PER_SEC的乘积返回毫微秒的数值,

#define NSEC_PER_SEC 1000000000ull 秒

#define NSEC_PER_MSEC 1000000ull 

#define USEC_PER_SEC 1000000ull

#define NSEC_PER_USEC 1000ull

<注意点>因为Main Dishpatch Queue在主线程的RunLoop中执行,所以比如在每隔1/60秒执行的RunLoop中,Block最快在三秒后执行,最慢在3秒+1/60秒后执行,并且在Main Dispatch Queue有大量追加处理货主线程本身的任务处理有延迟时,这个时间会增加

dispatch_time函数能获得从指定时间开始到第二个参数指定的时间间隔后的时间.

<二>补充,NSObject中提供的线程延迟方法

[self performSelector:@selector(run) withObject:nil afterDelay:2.0];

<三>通过NSTimer来延迟线程执行

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];

原文地址:https://www.cnblogs.com/denz/p/5277621.html