How to reset NSTimer? fast code

So, I create an application / game in which you press the button corresponding to the image until the timer expires and you lose. You get 1 second to press the button, and if you select the right button, the timer is reset and a new image appears. I'm having problems with a timer reseller. It fires after one second even after I try to reset it. Here is the code:

loadPicture () launches 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 is the resetTimer () method:

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

I think this may have something to do with NSRunloops? I'm not sure. I don’t even know what NSRunloop should do.

+8
ios reset xcode swift nstimer
source share
1 answer

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 line timer.invalidate (). 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) } 
+11
source share

All Articles