来自ViewController的Swift调用计时器

时间:2016-06-13 23:55:55

标签: ios swift

我有一个TimerManager类,我想在多个ViewControllers中访问,但我无法找到一个好方法。我的代码如下:

class TimerManager {

    private var timer: NSTimer
    private var timeRemaining: Int

    init(initialTime: Int) {
        self.timer = NSTimer()
        self.timeRemaining = initialTime
    }

    func startTimer() {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(TimerManager.update), userInfo: nil, repeats: true)
    }

    func endTimer() {
        self.timer.invalidate()
    }

    func getTimeRemaining() -> Int {
        return self.timeRemaining
    }

    @objc func update() {
        if self.timeRemaining > 0 {
            self.timeRemaining = self.timeRemaining - 1
        }
        else {
            endTimer()
        }
    } 
}

在我的ViewController中,我希望能够访问我的update()函数来更新我的实际页面上的计时器(UILabel),但是因为我的{{1}函数每秒调用一次,我不知道每次调用它时如何访问startTimer()。我简要地研究了update(),但我不确定它们是如何工作的,或者这对我的情况是否有用。

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

正如@sschale建议的那样,您可以通过使用单例来确保您将在代码中的任何位置访问同一实例。为此,您需要将init设置为private并提供静态成员变量来访问您的单个实例。

class TimerManager 
{
    static let sharedInstance = TimerManager()

    private var timer: NSTimer
    private var timeRemaining: Int

    private init()
    {
        let initialTime = 1
        self.timer = NSTimer()
        self.timeRemaining = initialTime
    }
    private init(initialTime: Int) 
    {
        self.timer = NSTimer()
        self.timeRemaining = initialTime
    }

    ...
}

然后在你的ViewControllers中你可以像这样调用它:

TimerManager.sharedInstance.startTimer()

答案 1 :(得分:0)

class TimerManager {

    private var timer: NSTimer
    private var timeRemaining: Int
    private var intervalBlock: (TimerManager -> ())?

    init(initialTime: Int) {
        self.timer = NSTimer()
        self.timeRemaining = initialTime
    }

    func startTimer(intervalBlock: (TimerManager -> ())? = nil) {
        self.intervalBlock = self
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(TimerManager.update), userInfo: nil, repeats: true)
    }

    func endTimer() {
        self.intervalBlock = nil
        self.timer.invalidate()
    }

    func getTimeRemaining() -> Int {
        return self.timeRemaining
    }

    @objc func update() {
        if self.timeRemaining > 0 {
            self.timeRemaining = self.timeRemaining - 1
            intervalBlock()
        }
        else {
            intervalBlock()
            endTimer()
        }
    } 
}

答案 2 :(得分:0)

以下是我从article

中发现的对后台队列执行Timer的最佳实现之一。
class RepeatingTimer {

    let timeInterval: TimeInterval

    init(timeInterval: TimeInterval) {
        self.timeInterval = timeInterval
    }

    private lazy var timer: DispatchSourceTimer = {
        let t = DispatchSource.makeTimerSource()
        t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
        t.setEventHandler(handler: { [weak self] in
            self?.eventHandler?()
        })
        return t
    }()

    var eventHandler: (() -> Void)?

    private enum State {
        case suspended
        case resumed
    }

    private var state: State = .suspended

    deinit {
        timer.setEventHandler {}
        timer.cancel()
        resume()
        eventHandler = nil
    }

    func resume() {
        if state == .resumed {
            return
        }
        state = .resumed
        timer.resume()
    }

    func suspend() {
        if state == .suspended {
            return
        }
        state = .suspended
        timer.suspend()
    }
}

用法:-

在您的任何ViewController中

例如:-

class MyViewController: UIViewController {

// MARK: - Properties
 var timer: RepeatingTimer!

// MARK: - ViewController LifeCycle

override func viewDidLoad() {
        super.viewDidLoad()
     timer =  RepeatingTimer(timeInterval: 1)
        timer.eventHandler = {
            print("Timer called")
        }

}