1

I'm kind of at a wall of what to do, the program runs, but the timer.invalidate() does not work? Any tips are welcome.

I worked with this program in the past and worked through it and the timer.invalidate() worked flawlessly. I do not believe that it has to do with the fact that I put it into a function because before it wasn't working when I was just typing "timer.invalidate()" instead of "stop()"

Whenever I click the button Cancel on the iOS simulator it just resets it back to 0, but keeps counting.

Thanks in advance.

import UIKit

class ViewController: UIViewController {
var timer = NSTimer()
var count = 0
@IBOutlet weak var timeDisplay: UILabel!
@IBAction func playButton(sender: AnyObject) {
    //play button
    var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
}

@IBAction func resetTimer(sender: AnyObject) {
    //cancel button
    stop()
    count = 0
    timeDisplay.text = "0"
}


@IBAction func pauseButton(sender: AnyObject) {
    stop()
}

func result() {
    count++
    timeDisplay.text = String(count)
}

func stop () {
    timer.invalidate()
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
 }
}
Justin
  • 65
  • 1
  • 9

1 Answers1

4

In playButton() you are defining another timer, that can't be invalidated from outside this function - so by calling timer.invalidate() you invalidate just var timer = NSTimer() which doesn't carry any set timer in it.

So replace

var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)

with

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
nicael
  • 18,550
  • 13
  • 57
  • 90
  • Thank you so much, I don't know how I missed that! My only excuse to missing that it is very late here! Haha, I appreciate it! @nicael – Justin Nov 07 '14 at 09:16
  • I was just waiting on the countdown! Cheers! @nicael – Justin Nov 07 '14 at 09:19