#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) CADisplayLink *displayLink;
@end
@implementation ViewController
{
dispatch_source_t _timer;
}
- (void)viewDidLoad {
[super viewDidLoad];
#if 0
// 第一種創(chuàng)建方式:
// [NSTimer scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> target:<#(nonnull id)#> selector:<#(nonnull SEL)#> userInfo:<#(nullable id)#> repeats:<#(BOOL)#>];
#endif
#if 0
// 第二種創(chuàng)建方式:
// CADisplayLink 與屏幕的刷新率寄疏,一般屏幕的默認刷新次數為60/s
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
// 修改刷新頻率坡贺,多少幀刷新一次
_displayLink.frameInterval = 60;
// 銷毀
// [_displayLink invalidate];
// _displayLink = nil;
// 當添加到RunLoop中會立即執(zhí)行
[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
#endif
#if 1
__block int j = 0;
// 第三種創(chuàng)建方式:
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
// intervarlInSeconds 每個多久執(zhí)行一次
// leewayInSeconds 允許出現(xiàn)多少誤差朗兵,0為最精準
dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
// 執(zhí)行的事件
dispatch_source_set_event_handler(_timer, ^{
NSLog(@"%d", j++);
});
// 執(zhí)行
dispatch_resume(_timer);
// 停止
// dispatch_source_cancel(timer);
#endif
}
- (void)update
{
static int index = 0;
NSLog(@"%d", index++);
if (index == 5)
{
// 暫停
_displayLink.paused = YES;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 繼續(xù)
_displayLink.paused = NO;
});
}
}
CADisplayLink是一個能讓我們以和屏幕刷新率相同的頻率將內容畫到屏幕上的定時器。
CADisplayLink 與 NSTimer 有什么不同?
iOS設備的屏幕刷新頻率是固定的晃洒,CADisplayLink在正常情況下會在每次刷新結束都被調用佑吝,精確度相當高围段。NSTimer的精確度就顯得低了點,比如NSTimer的觸發(fā)時間到的時候台腥,runloop如果在阻塞狀態(tài)宏赘,觸發(fā)時間就會推遲到下一個runloop周期。并且 NSTimer新增了tolerance屬性黎侈,讓用戶可以設置可以容忍的觸發(fā)的時間的延遲范圍察署。CADisplayLink使用場合相對專一,適合做UI的不停重繪峻汉,比如自定義動畫引擎或者視頻播放的渲染贴汪。NSTimer的使用范圍要廣泛的多脐往,各種需要單次或者循環(huán)定時處理的任務都可以使用。
在UI相關的動畫或者顯示內容使用 CADisplayLink比起用NSTimer的好處就是我們不需要在格外關心屏幕的刷新頻率了扳埂,因為它本身就是跟屏幕刷新同步的业簿。