驗證碼重發、活動倒計時這類需求經常出現,iOS 裡最常用的是 NSTimer 和 GCD 兩套方案,各有適用場合。
思路很簡單:用 scheduledTimerWithTimeInterval: 每秒觸發一次方法,在方法裡做減量判斷,歸零後 invalidate 即可。
secondsCountDown = 60;//60秒倒計時 countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; -(void)timeFireMethod{ secondsCountDown--; if(secondsCountDown==0){ [countDownTimer invalidate]; } }
注意兩點:NSTimer 會 retain target,循環引用導致頁面無法釋放的問題很常見,實戰中建議改用 block 版本的 API 或用代理表達式;另外它依賴 runloop,默認模式下滑列表時計時會暫停,需要時可加入 NSRunLoopCommonModes。
GCD 的 dispatch_source 不依賴 runloop,也不存在 target 持有問題,精度和穩定性更好,適合對準確性要求高的場景。
__block int timeout=300; //倒計時時間 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue); dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒執行 dispatch_source_set_event_handler(_timer, ^{ if(timeout<=0){ //倒計時結束,關閉 dispatch_source_cancel(_timer); dispatch_release(_timer); dispatch_async(dispatch_get_main_queue(), ^{ //設置界面的按鈕顯示 根據自己需求設置 內部細節省略 }); }else{ int minutes = timeout / 60; int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒後重新獲取驗證碼",minutes, seconds]; dispatch_async(dispatch_get_main_queue(), ^{ //設置界面的按鈕顯示 根據自己需求設置 內部細節省略 }); timeout--; } }); dispatch_resume(_timer);
使用 GCD 時要記住:source 創建後處於暫停狀態,必須調用 dispatch_resume 才會啟動;UI 更新一律切回主線程;結束時務必 cancel,避免懸空。
以上就是 iOS 倒計時的兩種實現方式。追求代碼簡潔可用 NSTimer,追求精度與穩定性建議首選 GCD。