說到定時(shí)器 ?也許大家并不陌生节槐,可能大家都只是對(duì)NSTimer比較熟悉吧,那么久來為大家介紹另外兩種不常見的方法吧
1.NSTimer(詳細(xì)的就不給大家介紹了)
+ (NSTimer*)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation*)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer*)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullableid)userInfo repeats:(BOOL)yesOrNo;
注意:上面?zhèn)z方法創(chuàng)建的timer需要將timer注冊(cè)到NSRunloop中才能開啟定時(shí)器的功能
? ? [[NSRunLoop currentRunLoop] addTimer:timer:forMode:NSRunLoopCommonModes];
+ (NSTimer*)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullableid)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer*)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation*)invocation repeats:(BOOL)yesOrNo;
ps:默認(rèn)將timer添加到當(dāng)前runloop中了蚂夕,所有無需添加
2. dispatch_source_create()
簡(jiǎn)單地分為幾個(gè)步驟 下面慢慢來講解
注意:這里創(chuàng)建的timer并需要設(shè)置為全局屬性,因?yàn)镚CD會(huì)自動(dòng)管理內(nèi)存蓝翰,當(dāng)回收的時(shí)候睦擂,你發(fā)現(xiàn)timer不起作用,就很尷尬了??
@property ?(nonamatic , strong ) dispatch_source_t ?timer;
? _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
? ? dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC );
? ? dispatch_source_set_event_handler(_timer, ^{
? ? ? ? flag ++;
? ? ? ? NSLog(@"flag = %d",flag);
? ? });
添加執(zhí)行事件代碼选浑。
? ? dispatch_resume(_timer);
手動(dòng)觸發(fā)
3.CADisplayLink
CADispalyLink displayLink = [CADisplayLink displayLinkWithTarget:selfselector:@selector(handleDisplayLink:)];
?[displayLink addToRunLoop:[NSRunLoopcurrentRunLoop] forMode:NSDefaultRunLoopMode]; ?
較為精準(zhǔn)蓝厌,與屏幕刷新幀率同步,多用戶視圖渲染或繪圖