Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

stop the timer which is executed after button click

I’ve a timer, after clicking a button I want the timer to begin, and when the timer gets 0 I want to stop the timer. I know I can do that with invalidate() function, but I can’t access the timer here’s code

    var timer = 5 {
        didSet {
            label.text = String(timer)
            
        }
    }
    @IBAction func onClickAnimate(_ sender: Any) {
        let timerCount = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
    }
    @objc func updateCounter(){
        if timer > 0 {
            timer -= 1
        }
        if timer == 0 {
            timer = 5
            timerCount.invalidate() // error is here
            }
    }

If I decide to create timerCount globally I get an error unrecognized selector sent to instance 0x600003b466a0"

any solution will be appericated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Solution 1 : make a variable

var timerCount:Timer!
@IBAction func onClickAnimate(_ sender: Any) {
    timerCount = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter(){
    if timer > 0 {
        timer -= 1
    }
    if timer == 0 {
        timer = 5
        timerCount.invalidate() 
   }
}

Solution 2 : use block

Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timerCount in
    if self.timer > 0 {
        self.timer -= 1
    }
    else
    if self.timer == 0 {
        self.timer = 5
        timerCount.invalidate() 
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading