1,最常見的計(jì)時(shí)器NSTimer (默認(rèn)放到defaultModel的runloop中,會(huì)受到runloop的影響)
//iOS1010以后的方法它類似,參數(shù)一:時(shí)間間隔參數(shù)二:是否一直執(zhí)行
[NSTimer timerWithTimeInterval:0.1 repeats:YES block:^(NSTimer *_Nonnull timer) {
NSLog(@"nstimeing");
}];
//唯一結(jié)束NSTimer計(jì)時(shí)器方法
[timer invalidate];
2,CA計(jì)時(shí)器(不用設(shè)置時(shí)間間隔,每秒運(yùn)行60次.默認(rèn)放到defaultModel的runloop中,會(huì)受到runloop的影響)
//創(chuàng)建計(jì)時(shí)器
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:selfselector:@selector(timerCall:)];
//添加到runloop中
[link addToRunLoop:[NSRunLoop mainRunLoop]forMode:NSDefaultRunLoopMode];
//調(diào)用方法
- (void)timerCall:(CADisplayLink *)link {
NSLog(@"linking");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//結(jié)束計(jì)時(shí)器的唯一方法
[link invalidate];
});
}
3,GCD計(jì)時(shí)器,(不受runloop影響,一般用在輪播圖等不需要受到runloop影響的情況下)
//GCD計(jì)時(shí)器在GCD資源里面
dispatch_source_t timer =dispatch_source_create(&_dispatch_source_type_timer, 0, 0,dispatch_get_main_queue());
//調(diào)用GCD的set方式
//參數(shù):1,GCD計(jì)時(shí)器??? 2,延遲幾秒后開始執(zhí)行?? 3,計(jì)時(shí)器間隔??? 4,計(jì)時(shí)器精度
dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,0.1*NSEC_PER_SEC, 0ull*NSEC_PER_SEC);
//handle方法(該方法在開啟了計(jì)時(shí)器時(shí)調(diào)用)
dispatch_source_set_event_handler(timer, ^{
NSLog(@"GCDtimering");
});
//開啟計(jì)時(shí)器
dispatch_resume(timer);
//GCD停止計(jì)時(shí)器方法,會(huì)觸發(fā)dispatch_source_set_cancel_handler方法
dispatch_source_cancel(timer);
dispatch_source_set_cancel_handler(timer, ^{
//如果在非arc模式下可以在該方法里釋放掉timer? (dispatch_release(timer);)
NSLog(@"計(jì)時(shí)器已經(jīng)停止了");
});