简体   繁体   中英

How can I use this Swift 3 Singleton as a Global Timer for my IOS project?

I've found this code on another thread (shown at the very bottom) for Swift 3 and can't seem to get it to work in my IOS project.

I know it's a Singleton, but I'll have to admit, I'm not sure how to USE it in my IOS project so that the timer will work across all ViewControllers.

Can I do the following? And if not, how can I use this?

var t = TimeModel.sharedTimer

t.startTimer(0.25, testing)

var counter = 0

func testing()
{
    counter += 1
    print("this is a test \(counter)")
}

What am I doing wrong?

class TimerModel: NSObject {
    static let sharedTimer: TimerModel = {
        let timer = TimerModel()
        return timer
    }()

    var internalTimer: Timer?
    var jobs = [() -> Void]()

    func startTimer(withInterval interval: Double, andJob job: @escaping () -> Void) {
        if internalTimer == nil {
            internalTimer?.invalidate()
        }
        jobs.append(job)
        internalTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(doJob), userInfo: nil, repeats: true)
    }

    func pauseTimer() {
        guard internalTimer != nil else {
            print("No timer active, start the timer before you stop it.")
            return
        }
        internalTimer?.invalidate()
    }

    func stopTimer() {
        guard internalTimer != nil else {
            print("No timer active, start the timer before you stop it.")
            return
        }
        jobs = [()->()]()
        internalTimer?.invalidate()
    }

    func doJob() {
        for job in jobs {
            job()
        }
    }

}

// Call the method like this.

let timer = TimerModel.sharedTimer

timer.startTimer(withInterval: 0.25) { 
    self.testing()
}

var counter = 0
func testing() {
    counter += 1
    print("this is a test \(counter)")
}

在此输入图像描述

If you want to call timer's selector method in another ViewController

You need to make some changes in your method ;

func startTimer(withInterval interval: Double, controller: UIViewController, andJob job: @escaping () -> Void) {
                    if timerTest != nil {
                    internalTimer.invalidate()
                    internalTimer = nil
                 }
                    jobs.append(job)
                    internalTimer = Timer.scheduledTimer(timeInterval: interval, target: controller, selector: #selector(doJob), userInfo: nil, repeats: true)
                }

Call in another ViewController

var t = TimeModel.sharedTimer.startTimer(0.25, self , testing)
    var counter = 0
     func doJob() {
        counter += 1
        print("this is a test \(counter)")
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM