集團(tuán)項(xiàng)目需要在網(wǎng)絡(luò)請(qǐng)求的時(shí)候添加一個(gè)計(jì)時(shí)器请唱,NSTimer有什么缺點(diǎn)我就不說了空入,今天說下GCD做計(jì)時(shí)器的一些心得。
創(chuàng)建計(jì)時(shí)器
@property (nonatomic, strong) dispatch_source_t timer;//創(chuàng)建一個(gè)全局的timer
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);//開始時(shí)間:從現(xiàn)在開始1秒后開始
dispatch_source_set_timer(self.timer, start, (int64_t)(1.0 * NSEC_PER_SEC), 0);
dispatch_source_set_event_handler(self.timer, ^{
// 計(jì)時(shí)器計(jì)時(shí)中需要執(zhí)行的方法
[self timerMethod1];
});
//開啟計(jì)時(shí)器
dispatch_resume(self.timer);
//關(guān)閉計(jì)時(shí)器
dispatch_cancel(self.timer);
使用這個(gè)方法關(guān)閉計(jì)時(shí)器咖城,timer會(huì)置nil茬腿,如果循環(huán)使用計(jì)時(shí)器呼奢,再次執(zhí)行開啟計(jì)時(shí)器的方法,就會(huì)出現(xiàn)閃退情況切平,可以使用下面的方法暫停計(jì)時(shí)器
dispatch_suspend(self.timer);
這樣下次啟動(dòng)計(jì)時(shí)器就可以正常使用了握础。