Multiple timers at once ios

I am making an app where the user can have multiple timers going at once and see them in a list view.

I am aware that there are 2 main options for working out time:

  • Subtract the date started from current date (current date-start date)

OR

  • Use an NSTimer and take away 1 second every second from each active timer.

I have previously been using the latter, but having looked around the internet I am starting to think that the data one may be better.

Please could you let me know which you think is best to use, and if you chose the first one (dates), please could you provide some sample code on how to use it.

2 thoughts on “Multiple timers at once ios”

  1. You use both. You have one Timer that repeats every second. The handler for the Timer then iterates through your list of start dates for each of the user’s timers and you update the display for each based on the current date.

  2. You can Use an NSTimer and take away 1 second every second from each active timer. You can use this class.
    class CustomTimer {
    typealias Update = (Int)->Void
    var timer:Timer?
    var count: Int = 0
    var update: Update?

    init(update:@escaping Update){
    self.update = update
    }
    func start(){
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)
    }
    func stop(){
    if let timer = timer {
    timer.invalidate()
    }
    }
    /**
    * This method must be in the public or scope
    */
    @objc func timerUpdate() {
    count += 1;
    if let update = update {
    update(count)
    }
    }
    }

    To use multiple timer you can create multiple instance of CustomTimer, Example Code:
    let timer1 = CustomTimer { (seconds) in
    // do whatever you want
    }
    timer1.start()
    let timer2 = CustomTimer { (seconds) in
    // do whatever you want
    }
    timer2.start()

Leave a Reply

Your email address will not be published.