iOS幾種常見計(jì)時(shí)器

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)停止了");

});

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容