1. GCD延时执行
1.1 延时执行常用的方法有2种
分别是 performSelector 和NSTimer
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
其中 performSelector的用法
[self performSelector:@selector(test) withObject:nil afterDelay:2.0];
其中 NSTimer的用法
/*
第一参数:延迟的时间,也就是多少秒后执行
第二参数:指定一个对象发送,通常是当前界面,self
第三参数:调用的函数
第四参数:计时器的用户信息
第五参数:YES,就会循环执行,直至失效。NO,只会执行一次
*/
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:NO];
1.2 GCD延时执行的方法
// 主队列
// dispatch_queue_t queue = dispatch_get_main_queue();
// 开线程
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
/*
第一参数: DISPATCH_TIME_NOW 从现在开始计算时间
第二参数(delayInSeconds): 要延迟的时间 2.0 GCD时间单位:纳秒
第三参数(dispatch_get_main_queue): 主队列
第四参数^{ }:写需要执行的代码
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
NSLog(@"GCD------%@",[NSThread currentThread]);
});
2. GCD一次性代码
- 作用:一次性代码:整个应用程序运行过程中只会被执行一次 不能放在懒加载中,应用场景:单例模式
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"----once-----");
});
3. GCD知识点补充
- GCD中的定时器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 1.创建GCD中的定时器
/*
第一参数(DISPATCH_SOURCE_TYPE_TIMER): source 的类型 DISPATCH_SOURCE_TYPE_TIMER 表示是定时器
第二参数(0): 描述信息,线程ID
第三参数(0): 更详细的描述信息
第四参数(<#dispatchQueue#>): 队列,决定GCD定时器中的任务在哪个线程中执行
*/
// 注意:需要strong 强引用后才能运行使用,不强引用运行期间可能会被释放掉
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
// 2. 设置定时器(起始时间 | 间隔时间 | 精准度)
/*
第一参数(timer): 创建的定时器对象
第二参数(DISPATCH_TIME_NOW): 起始时间, DISPATCH_TIME_NOW 从现在开始计时
第三参数(<#intervalInSeconds#> * NSEC_PER_SEC): 间隔时间,2.0 --- GCD 中时间单位是纳秒,
第四参数(<#leewayInSeconds#> * NSEC_PER_SEC): 精准度 绝对精准 0
*/
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
// 3. 设置定时器执行的任务 - 通过block块的方式操作
dispatch_source_set_event_handler(timer, ^{
NSLog(@"GCD --- %@",[NSThread currentThread]);
});
// 4.启动执行
dispatch_resume(timer);
self.timer = timer;
// 启动程序,不执行的原因:是因为2秒后timer被释放