SWIFT - 多个NSTimers

时间:2014-09-22 11:33:56

标签: timer swift nstimer

在尝试管理SWIFT中的多个NSTimers时,我遇到了一个小问题。无论我尝试什么,它只会使我创建的最后一个计时器无效。但我需要能够通过选择使任何计时器无效。

有没有办法创建一个参考ID,然后我可以用它来选择我想要无效的特定NSTimer?任何帮助都会很棒。

这是我的代码片段。

import UIKit

var myTimer:NSTimer!

class TimerManager: NSObject {

}

public class Timer {
// each instance has it's own handler
private var handler: (timer: NSTimer) -> () = { (timer: NSTimer) in }

public class func start(duration: NSTimeInterval, repeats: Bool, handler:(timer: NSTimer)->()) {
    var t = Timer()
    t.handler = handler
    myTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: t, selector: "processHandler:", userInfo: nil, repeats: repeats)
}

@objc private func processHandler(timer: NSTimer) {
    self.handler(timer: timer)
}
}

class countdown{
//handles the countdown for the timer and invalidates when it reaches 0
var y = 0

func begin(length:Int) {

    y = length

    let delta = 1
    let delay = 1.0
    Timer.start(delay, repeats: true) {
        (t: NSTimer) in

        self.y -= delta
        println(self.y)

        if (self.y <= 0) {
            t.invalidate()
        }
    }
}

func end () {
    println("timer stopped")
    myTimer.invalidate()
}
}

我像这样创建计时器:

 countdownTimer.begin(120) //time length in seconds ... 120 = 2 mins

停止计时器:

 countdownTimer.end() 

1 个答案:

答案 0 :(得分:4)

您可以创建一个保留NSTimer对象的字典。请注意, timerManager 需要在全局范围内定义。希望它能够解决问题。

class TimerManager {

    var _timerTable = [Int: NSTimer]()
    var _id: Int = 0

    /*! Schedule a timer and return an integer that represents id of the timer
     */
    func startTimer(target: AnyObject, selector: Selector, interval: NSTimeInterval) -> Int {
        var timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: target, selector: selector, userInfo: nil, repeats: true)
        _id += 1
        _timerTable[_id] = timer
        return _id
    }

    /*! Stop a timer of an id
    */
    func stopTimer(id: Int) {
        if let timer = _timerTable[id] {
            if timer.valid {
                timer.invalidate()
            }
        }
    }

    /*! Returns timer instance of an id
    */
    func getTimer(id: Int) -> NSTimer? {
        return _timerTable[id]
    }

}

// This needs to be delcared at global scope, serving as "singleton" instance of TimerManager
let timerManager = TimerManager()

以下代码会创建一个新计时器。

var aTimer = timerManager.startTimer(self, selector: Selector("timerFunction"), interval: 1)

要停止计时器,只需将id传递给 stopTimer(id:Int)

/* Code ... */
timerManager.stopTimer(aTimer)

另请注意, getTimer 方法返回带有id的实际实例。

此致