倒計時有兩類典型場景:一是短信驗證碼的 60 秒冷卻,二是電商活動的跨天倒數。前者用 NSTimer 更直接,後者用 GCD 定時源更合適,下面分別說明。
思路是每秒觸發一次方法,在方法裡遞減計數並刷新按鈕標題。
// 創建定時器,每秒執行一次 changeTime:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(changeTime:)
userInfo:nil
repeats:YES];
- (void)changeTime:(NSTimer *)timer {
UIButton *button = (UIButton *)[self.view viewWithTag:99];
if (count == 0) {
[timer invalidate]; // 計時結束,必須註銷
count = 59; // 重置,供下次使用
[button setTitle:@"重新獲取" forState:UIControlStateNormal];
button.userInteractionEnabled = YES;
button.alpha = 1;
} else {
[button setTitle:[NSString stringWithFormat:@"%d s", count] forState:UIControlStateNormal];
count--;
}
}
使用時記得在離開頁面前 invalidate,否則 timer 會被 runloop 持有而導致控制器無法釋放。
活動倒計時通常基於服務器時間計算差值,且需要展示天、時、分、秒,用 GCD 的 dispatch source 更靈活,也不依賴 runloop。
頭文件中聲明定時源:
// 倒計時定時器 dispatch_source_t _timer;
實現部分:
// 時間戳格式化
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
// 字符串轉 NSDate
NSDate *endDate = [dateFormatter dateFromString:_EndTime];
NSDate *startDate = [dateFormatter dateFromString:_StartTime];
NSDate *currentDate = [dateFormatter dateFromString:_CurrentTime];
// 距活動結束的剩餘秒數
NSTimeInterval timeInterval = [endDate timeIntervalSinceDate:currentDate];
// 活動已進行的秒數
NSTimeInterval StartToNow = [currentDate timeIntervalSinceDate:startDate];
__block int timeout = timeInterval;
__block int StartTimeout = StartToNow;
if (timeout != 0) {
// 全局並發隊列,四個優先級可選:
// DISPATCH_QUEUE_PRIORITY_HIGH / DEFAULT / LOW / BACKGROUND
// 第二個參數目前系統保留,傳 0 即可
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 每秒觸發一次
_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 || StartTimeout <= 0) {
dispatch_source_cancel(_timer);
_timer = nil;
// 定時器回調在子線程,刷新 UI 必須切主線程
dispatch_async(dispatch_get_main_queue(), ^{
dayLabel.text = @"0天";
hourLabel.text = @"00 :";
minLabel.text = @"00 :";
secLabel.text = @"00";
label.text = @"搶購結束!!!";
});
} else {
label.text = @"搶購剩余時間:";
int days = (int)(timeout / (3600 * 24));
int hours = (int)((timeout - days * 24 * 3600) / 3600);
int minute = (int)(timeout - days * 24 * 3600 - hours * 3600) / 60;
int second = timeout - days * 24 * 3600 - hours * 3600 - minute * 60;
dispatch_async(dispatch_get_main_queue(), ^{
dayLabel.text = days == 0 ? @"0天" : [NSString stringWithFormat:@"%d天", days];
hourLabel.text = hours < 10 ? [NSString stringWithFormat:@"0%d :", hours]
: [NSString stringWithFormat:@"%d :", hours];
minLabel.text = minute < 10 ? [NSString stringWithFormat:@"0%d :", minute]
: [NSString stringWithFormat:@"%d :", minute];
secLabel.text = second < 10 ? [NSString stringWithFormat:@"0%d", second]
: [NSString stringWithFormat:@"%d", second];
});
timeout--;
}
});
dispatch_resume(_timer); // 創建後處於暫停狀態,必須 resume 才會開始
}
NSTimer 依賴 runloop,在滾動列表等切換 tracking mode 的場景下會停止觸發,需要通過 NSRunLoopCommonModes 解決;GCD 定時源不依賴 runloop,精度更高,也不會造成 timer 與宿主對象的循環引用。因此單純的驗證碼倒計時用 NSTimer 足夠,而電商活動倒計時、需要與服務器時間對齊的場景,推薦 GCD 方案。無論哪一種,都要記得在合適的時機(如 viewDidDisappear 或 dealloc)調用 invalidate 或 dispatch_source_cancel 釋放。