I´m trying to create a hockey game clock-app with a main game clock and a start/stop-button. But I´m having trouble with my stopGameclock function. The timer won't invalidate. From searching other questions here I think it has to do with my:
var gameclockTimer = NSTimer()
Seams I can't use this var to invalidate the timer. I know the function works because I can see "stop"
func stopGameclock() {
self.gameclockTimer.invalidate()
print("stop")
Is there any way to make make this function invalidate my timer?
Unfortunately the answers I found so far haven't helped me without the need to put the timer and functions in the ViewController class.
The reason I want to keep the timer in a separate class is because later on I will add several penalty clocks/timers and I want to have them in separate classes to keep it easy to overview.
The complete code looks like this so far:
// ViewController.swift
import UIKit
class ViewController: UIViewController {
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLoad() {
super.viewDidLoad()
gameclockLabel.text = "00:00"
}
var startstopPushed: Bool = false
@IBOutlet weak var gameclockLabel: UILabel!
@IBOutlet weak var startstop: UIButton!
@IBAction func startStopbutton(sender: AnyObject) {
if startstopPushed == false {
Gameclock().startGameclock()
startstop.setImage(UIImage(named: "stop.png"), forState: UIControlState.Normal)
startstopPushed = true
}
else
{
Gameclock().stopGameclock()
startstop.setImage(UIImage(named: "start.png"), forState: UIControlState.Normal)
startstopPushed = false
}
}
}
class Gameclock : NSObject {
var gameclockTimer = NSTimer()
var timeString: String = ""
var seconds = 0
var minutes = 0
func startGameclock() {
gameclockTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateGameclock"), userInfo: nil, repeats: true)
}
func stopGameclock() {
self.gameclockTimer.invalidate()
print("stop")
}
func updateGameclock() {
seconds += 1
if seconds == 60 {
minutes += 1
seconds = 0
}
let secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"
timeString = "\(minutesString):\(secondsString)"
print(timeString)
}
}
the problem is that each time you're accessing GameClock, you are creating a new instance of it - so the instance that you're stopping is not the one that you created.
You can keep all of the functionality in the
GameClock
class, but you will need to define a variable inViewController
to access it.and then in your
startstopPushed
method make these changesI think this should work:
I create a var gameClock just once which represents your game clock class and then run the methods on this one class