倒數計時是活動頁、限時優惠這類需求的常客。這份程式碼示範如何以 NSTimer 為核心,計算距離目標時刻的剩餘天、時、分、秒,並即時更新到畫面上。詳細邏輯請對照註解閱讀。
// 啟動計時器:每秒觸發一次
// [NSTimer scheduledTimerWithTimeInterval:1.0
// target:self
// selector:@selector(timerFireMethod:)
// userInfo:nil
// repeats:YES];
- (void)timerFireMethod:(NSTimer *)theTimer {
BOOL timeStart = YES;
NSCalendar *cal = [NSCalendar currentCalendar]; // 日曆物件
// 初始化目標時間元件
NSDateComponents *endTime = [[NSDateComponents alloc] init];
NSDate *today = [NSDate date]; // 當前時間
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateString = [dateFormatter dateFromString:todate];
NSString *overdate = [dateFormatter stringFromDate:dateString];
// 年月日時分秒只需解析一次,用 static 保存結果
static int year;
static int month;
static int day;
static int hour;
static int minute;
static int second;
if (timeStart) {
// 從格式化字串中取出各時間元件
year = [[overdate substringWithRange:NSMakeRange(0, 4)] intValue];
month = [[overdate substringWithRange:NSMakeRange(5, 2)] intValue];
day = [[overdate substringWithRange:NSMakeRange(8, 2)] intValue];
hour = [[overdate substringWithRange:NSMakeRange(11, 2)] intValue];
minute = [[overdate substringWithRange:NSMakeRange(14, 2)] intValue];
second = [[overdate substringWithRange:NSMakeRange(17, 2)] intValue];
timeStart = NO;
}
[endTime setYear:year];
[endTime setMonth:month];
[endTime setDay:day];
[endTime setHour:hour];
[endTime setMinute:minute];
[endTime setSecond:second];
NSDate *overTime = [cal dateFromComponents:endTime]; // 組裝出目標 NSDate
// 取得兩個時間的差值,藉此統一為基準時區的計算
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit
| NSDayCalendarUnit | NSHourCalendarUnit
| NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *d = [cal components:unitFlags
fromDate:today
toDate:overTime
options:0];
NSString *t = [NSString stringWithFormat:@"%d", [d day]];
NSString *h = [NSString stringWithFormat:@"%d", [d hour]];
NSString *fen = [NSString stringWithFormat:@"%d", [d minute]];
if ([d minute] < 10) {
fen = [NSString stringWithFormat:@"0%d", [d minute]]; // 補零對齊
}
NSString *miao = [NSString stringWithFormat:@"%d", [d second]];
if ([d second] < 10) {
miao = [NSString stringWithFormat:@"0%d", [d second]];
}
[_longtime setText:[NSString stringWithFormat:@"%@天 %@:%@:%@", t, h, fen, miao]];
if ([d second] > 0) {
// 計時尚未結束,do_something
}
else if ([d second] == 0) {
// 計時結束,do_something
}
else {
// 時間已過,計時器失效
[theTimer invalidate];
}
}
為什麼用 static 暫存時間元件。目標時刻通常是一個固定字串,沒有必要每秒重新解析一次。用 static 變數把年月日時分秒留住,只在第一次進入時做字串切割,能省下不必要的反覆運算。
為什麼用 NSDateComponents 做差值。直接拿兩個 NSDate 相減只能得到總秒數,要拆成天時分秒还得自己做除法與餘數。交給 NSCalendar 的 components:fromDate:toDate:options:,系統會自動處理閏年、跨月、跨時區等細節,程式碼乾淨得多。
計時器失效的時機。程式碼裡判斷的是 [d second] > 0。嚴格說來這裡的語意應該是「目標時間是否已過」,用秒數是否為負來判斷會更準確——因為當剩餘時間恰好是整分鐘(秒數為 0)時,這段邏輯會誤判為計時結束。實務上建議改成比較兩個 NSDate 的先後,或判斷 d 的各元件是否全部為 0。
NSTimer 的兩個常見地雷。
NSDefaultRunLoopMode,因此當使用者拖動 UIScrollView 或 TableView 時,計時器會暫停觸發。若需要持續更新,要改用 NSRunLoopCommonModes 重新加入。invalidate,或在 iOS 10 之後改用 block 版本的 timerWithTimeInterval:repeats:block: 並搭配 weak self。時間顯示的建議。若要顯示天數,用 NSDateComponents 一次取出天、時、分、秒是最省事的做法;但若你的倒數需要精準到「總共剩幾天幾小時」,建議固定以「天」為最大單位計算,避免月、年這類變長單位帶來的誤差。
把上述幾點調整過後,這份倒數計時就能穩定跑在真實的專案裡了。