NSTimer 是 iOS 裡最直覺的定時器機制,通常用 scheduledTimerWithTimeInterval 建立週期性任務。下面以一個倒數計時器為例,說明實作時容易踩到的幾個坑。
點擊按鈕後啟動一個每秒觸發一次的倒數計時器:
func demoNSTimer() {
btn.userInteractionEnabled = !btn.userInteractionEnabled
countdown = countTimer
if timer != nil {
timer.invalidate()
timer = nil
}
timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self,
selector: "actionNSTimer",
userInfo: nil,
repeats: true)
timer.fire()
}
計時器觸發時的處理:
func actionNSTimer() {
if countdown < 1 {
if timer != nil {
countdown = countTimer
timer.invalidate()
timer = nil
lb.text = countdown
lb.alpha = 1.0
}
return
}
lb.text = countdown
lb.transform = CGAffineTransformMakeScale(1.0, 1.0)
lb.alpha = 1.0
countdown = countdown - 1
UIView.animateWithDuration(1.0, animations: {
self.lb.transform = CGAffineTransformMakeScale(2.0, 2.0)
self.lb.alpha = 0.0
}) { (finished) in
if self.countdown == 0 {
self.btn.userInteractionEnabled = true
}
}
}
計時器執行途中若要暫停,不能用 invalidate(那是銷毀),正確做法是改寫 fireDate 為一個遙遠的未來時間;恢復時再改回過去時間即可。
if timer.valid {
timer.fireDate = NSDate(timeIntervalSinceNow: 3600) // 暫停
// timer.fireDate = NSDate.distantPast() // 恢復
}
實務上常見的需求是:App 進入背景時暫停計時。可以在 applicationWillResignActive 發送通知暫停,在 applicationDidBecomeActive 再通知恢復,避免回前景後時間已經跳了一大截。
NSTimer 預設被加進 NSDefaultRunLoopMode,這會導致一個經典問題:當它掛在 UITableView 或 UIScrollView 上時,畫面一滾動,RunLoop 切換到追蹤模式,計時器就停止觸發了(cell 重用並非真正原因)。解法是把它加入共同模式:
// 修改 mode,滾動時也能收到計時器訊息 NSRunLoop.currentRunLoop().addTimer(timer, forMode: .CommonModes)
使用 NSURLConnection 建立非同步請求時情況相同,預設也是 DefaultRunLoopMode,需要同樣處理:
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false) connection.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: .CommonModes) connection.start()