您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 使用 NSTimer 實作定時任務時該注意的幾件事

編輯:iOS 開發綜合

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 再通知恢復,避免回前景後時間已經跳了一大截。

RunLoop 模式

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()
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved