GCD定时器
1 @interface ViewController () 2 3 4 5 /** 定时器对象 */ 6 7 @property(nonatomic,strong)dispatch_source_t timer; 8 9 @end 10 11 12 13 @implementation ViewController 14 15 16 17 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 18 19 { 20 21 /* 22 23 总结:GCD定时器:会自动开启一条子线程,子线程中也会自己开启了runloop.自己创建,自己管理,全不用我们手动管理 24 25 */ 26 27 28 29 //一.创建定时器对象 30 31 //这个方法只要敲:(dispatach_source...timer..) 32 33 //01参数:要创建的source 是什么类型的 34 35 //(DISPATCH_SOURCE_TYPE_TIMER)定时器 36 37 //04参数:队列 ----线程 决定block 在哪个线程中调用 38 39 40 41 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0)); 42 43 44 45 //二.设置定时器 46 47 //01参数:定时器对象 48 49 //02参数:开始时间 (DISPATCH_TIME_NOW) 什么时候开始执行第一次任务 50 51 //03参数:间隔时间 GCD时间单位:纳秒 52 53 //04参数:leewayInSeconds精准度:允许的误差: 0 表示绝对精准 54 55 dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); 56 57 58 59 //三.定时器每隔一段时间就要执行任务(block回调) 60 61 dispatch_source_set_event_handler(timer, ^{ 62 63 NSLog(@"GCD----%@",[NSThread currentThread]);//(当前线程是子线程) 64 65 }); 66 67 68 69 //四.恢复(默认是停止的) 70 71 dispatch_resume(timer); 72 73 74 75 self.timer = timer; //一定要用强指针引着 76 77 }