延迟执行的方法
[self performSelect:@selector(task) withObject:nil afterDelay:2.0];
使用定时器方法延迟执行
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:NO];
使用GCD方法延迟,优点是可以在子线程执行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{...});
不受RunLoopMode模式影响的定时器-- GCD的定时器
// 创建GCD中的定时器 定时器在类中必须有强引用,不然就被释放掉了无法启动,使用strong类型.
@property(nonatomic, strong) dispatch_source_t timer;
// 1.表示定时器 2.3.表示描述信息,用于创建其他事件用的参数 4.队列,决定定时器在哪个线程执行
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0,0));
self.timer = timer; // 只是为了定时器不被释放掉
// 2.设置定时器(起始时间)
// 1.定时器对象 2.起始时间,从现在开始计时 3.间隔时间(纳秒) 4.精准度,0代表绝对精准.
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
// 3.设置定时器执行的任务
dispatch_source_set_event_handler(timer, ^{...});
// 4.启动定时器
dispatch_resume(timer);