倒計時看起來簡單,實作時卻容易忽略幾個細節:計時器不該無限遞迴建立、目標時間要用絕對時間戳而非累加計數、以及 dealloc 中必須 invalidate。下面以「十分鐘倒數」為例說明。
#import "ViewController.h" #import "QSSDateHelper.h" @interface ViewController () @property (nonatomic, strong) UIButton *btn; @property (nonatomic, assign) BOOL isTouch; @property (nonatomic, assign) NSInteger time; @property (nonatomic, assign) int year; @property (nonatomic, assign) int mouth; @property (nonatomic, assign) int day; @property (nonatomic, assign) int hour; @property (nonatomic, assign) int minute; @property (nonatomic, assign) int second; @property (nonatomic, assign) int myTouchSecond; @property NSDate *touchDate; @property NSCalendar *cal; @property NSTimer *timer; @end
計時器一定要在 dealloc 中收尾,否則 controller 無法釋放:
- (void)dealloc {
[self.timer invalidate];
self.timer = nil;
self.time = 0;
}
核心的時間差計算:
- (void)timerFireMethod:(NSTimer *)timer {
// 目標時間 = 按下當下的時間戳 + 10 分鐘
int targetSecond = self.myTouchSecond + 10 * 60;
// 把目標秒數轉為 NSDate,再取出各時間單位
NSDate *dd = [NSDate dateWithTimeIntervalSince1970:targetSecond];
unsigned int time2 = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *t2 = [cal components:time2 fromDate:dd];
// 開始倒計時的時間
unsigned int time = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *t = [self.cal components:time fromDate:self.touchDate];
NSLog(@"開始倒計時的時間:%d天%d小時%d分鐘%d秒",
(int)t.day, (int)t.hour, (int)t.minute, (int)t.second);
// 目標時間
NSLog(@"目標時間:%d天%d小時%d分鐘%d秒",
(int)t2.day, (int)t2.hour, (int)t2.minute, (int)t2.second);
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 以「現在」與「目標」相減,得到剩餘時間差
NSDate *nowhhhhh = [NSDate date];
NSDateComponents *d = [calendar components:unitFlags fromDate:nowhhhhh toDate:dd options:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
[NSString stringWithFormat:@"%d分鐘%d秒", (int)[d minute], (int)[d second]]
message:@"倒計時"
delegate:self
cancelButtonTitle:@"我知道了"
otherButtonTitles:nil];
alert.delegate = self;
[alert show];
}
啟動倒計時:第一次觸發時記錄基準時間,之後改由計時器驅動。
- (void)releaseTime {
self.time++;
self.isTouch = YES;
if (self.time == 1) {
NSLog(@"開始倒計時");
// 抓取當前時間的各個單位
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
unsigned int time = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *t = [cal components:time fromDate:now];
self.year = (int)[t year];
self.mouth = (int)[t month];
self.day = (int)[t day];
self.hour = (int)[t hour];
self.minute = (int)[t minute];
self.second = (int)[t second];
// 記錄絕對時間戳,作為倒數基準
NSTimeInterval time2 = [[NSDate date] timeIntervalSince1970];
self.myTouchSecond = time2;
NSLog(@"date\n%d", self.myTouchSecond);
self.touchDate = now;
self.cal = cal;
} else {
// 每秒重新排一次,讓 fireDate 立刻生效
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerFireMethod:)
userInfo:nil
repeats:NO];
[self.timer setFireDate:[NSDate distantPast]];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
值得提醒的是,這份寫法用 repeats:NO 搭配 setFireDate 達到週期效果,每輪都要重建計時器,開銷偏高。更穩妥的做法是用 repeats:YES 建立一次,並以「目標時間戳減當前時間戳」推算剩餘秒數——這樣即使 App 進入背景導致計時器暫停,回到前景也不會出現倒數延誤的問題。