今天要和大家分享的是利用GCD實(shí)現(xiàn)定時(shí)器,一向少?gòu)U話的我,就不和大家墨跡了,直接上代碼,我這里以實(shí)現(xiàn)驗(yàn)證碼按鈕以例:
//首先是驗(yàn)證碼間隔時(shí)間
__block int timeout = 59;
//建立一個(gè)全局隊(duì)列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//創(chuàng)建一個(gè)定時(shí)器事件源
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//設(shè)置處理事件的時(shí)間間隔這里設(shè)置1S
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
//然后就是響應(yīng)事件
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計(jì)時(shí)結(jié)束,關(guān)閉
dispatch_source_cancel(_timer);//關(guān)閉定時(shí)器
dispatch_async(dispatch_get_main_queue(), ^{
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
[btn setTitle:@"獲取驗(yàn)證碼" forState:UIControlStateNormal];
btn.userInteractionEnabled = YES;
});
}else{
//int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[btn setTitle:[NSString stringWithFormat:@"%@秒重發(fā)",strTime] forState:UIControlStateNormal];
[UIView commitAnimations];
btn.userInteractionEnabled = NO;
});
timeout--;
}
});
//開(kāi)啟定時(shí)器
dispatch_resume(_timer);
就這樣吧 希望能夠?qū)Υ蠹矣兴鶐椭?,如果大家想多了解下dispatch_source 大家可以自己到網(wǎng)上搜下,功能挺強(qiáng)大的;