手機驗證碼是每個 App 都會遇到的功能:按下「取得驗證碼」後,按鈕要進入 60 秒倒數,倒數期間不能重複點擊,歸零後才恢復可點。這個需求用 NSTimer 就能漂亮解決。
int secondsCountDown; // 倒計時總時長 NSTimer *countDownTimer; UILabel *labelText;
// 建立顯示用的 label
labelText = [[UILabel alloc] initWithFrame:CGRectMake(10, 120, 120, 36)];
[self.view addSubview:labelText];
// 設定總秒數
secondsCountDown = 60;
// 每 1 秒觸發一次 timeFireMethod
countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self selector:@selector(timeFireMethod)
userInfo:nil repeats:YES];
labelText.text = [NSString stringWithFormat:@"%d", secondsCountDown];
- (void)timeFireMethod {
secondsCountDown--;
labelText.text = [NSString stringWithFormat:@"%d", secondsCountDown];
if (secondsCountDown == 0) {
[countDownTimer invalidate];
[labelText removeFromSuperview];
}
}
一、計時器一定要 invalidate。scheduledTimerWithTimeInterval 建立的 timer 會被 RunLoop 強引用,同時它也強引用 target,形成循環引用。不 invalidate 的話控制器永遠不會被釋放。
二、用絕對時間而非累加。NSTimer 的觸發並不精準,當 App 進入背景或系統忙碌時會累積誤差,60 秒可能變成 70 秒。比較好的做法是記錄一個 endDate,每次觸發時用 [endDate timeIntervalSinceNow] 反推剩餘秒數:
NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:60];
// 每次 callback 中
NSInteger left = (NSInteger)[endDate timeIntervalSinceNow];
if (left <= 0) { /* 結束 */ }
三、進入背景時的處理。iOS 會暫停背景中的 timer,回前景後可能不會立刻補觸發。搭配上面「用時間差計算」的寫法可以自然解決這個問題。
四、切換 RunLoop Mode。如果倒數文字放在可滾動的頁面上,使用者拖動列表時 timer 會暫停(因為預設只綁在 NSDefaultRunLoopMode),需要改用 NSRunLoopCommonModes。
[[NSRunLoop currentRunLoop] addTimer:countDownTimer forMode:NSRunLoopCommonModes];
最後補充:iOS 10 之後若要在 App 關閉時也發出提醒,應該改用 UNNotificationRequest 的排程通知,而不是靠自己跑 timer。