Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset NSTimer? swift code

So I'm creating an app/game where you tap a button corresponding to a picture before the timer runs out and you lose. You get 1 second to tap the button, and if you choose the right button then the timer resets and a new picture comes up. I'm having trouble reseting the timer. It fires after one second even after I attempt to reset it. Here's the code:

loadPicture() runs off viewDidLoad()

func loadPicture() {
    //check if repeat picture
    secondInt = randomInt
    randomInt = Int(arc4random_uniform(24))
    if secondInt != randomInt {
        pictureName = String(self.PicList[randomInt])
        image = UIImage(named: pictureName)
        self.picture.image = image
        timer.invalidate()
        resetTimer()

    }
    else{
        loadPicture()
    }
}

and here's the resetTimer() method:

func resetTimer(){
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("gameOverTimer"), userInfo: nil, repeats: false)

}

I think it may have something to do with NSRunloops? I'm not sure. I don't even know what a NSRunloop is to be honest.

like image 268
LuKenneth Avatar asked Jul 29 '15 03:07

LuKenneth


People also ask

How do I stop a reboot timer in Swift?

We don't pause/resume Timer instances. We stop them with invalidate() . And when you want to restart it, just create new timer. Please refer to the Timer documentation, also available right in Xcode.


1 Answers

So I finally figured it out...

I had to make a separate function to start the timer by initializing it. And in the resetTimer() function I added the timer.invalidate() line. So my code looks like this:

func loadPicture() {
    //check if repeat picture
    secondInt = randomInt
    randomInt = Int(arc4random_uniform(24))
    if secondInt != randomInt {
        pictureName = String(self.PicList[randomInt])
        image = UIImage(named: pictureName)
        self.picture.image = image
        resetTimer()

    }
    else{
        loadPicture()
    }
}
func startTimer(){
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("gameOverTimer"), userInfo: "timer", repeats: true)
}

func resetTimer(){

    timer.invalidate()
    startTimer()
}

EDIT

With the new selector syntax it looks like this:

func startTimer(){
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(NameOfClass.startTimer), userInfo: "timer", repeats: true)
}
like image 50
LuKenneth Avatar answered Oct 06 '22 03:10

LuKenneth