Home > OS >  stop the timer which is executed after button click
stop the timer which is executed after button click

Time:11-24

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

CodePudding user response:

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() 
    }
}

CodePudding user response:

You should put timerCount outside the function but inside the class so that you can access it:

class ViewController: UIViewController {
   let timerCount: Timer = Timer()
}

Then, remove let keyword.

You can now access your timerCount.

CodePudding user response:

Make Global variable in Class like:

var timerCount = Timer()

Boom!!!... Now you can access it.

  • Related