ios


swift invalidate timer in function


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 in ViewController to access it.
class ViewController: UIViewController {
var gameClock = Gameclock()
and then in your startstopPushed method make these changes
if startstopPushed == false {
//Gameclock().startGameclock()
gameClock.startGameclock()
startstop.setImage(UIImage(named: "stop.png"), forState: UIControlState.Normal)
startstopPushed = true
}
else
{
//Gameclock().stopGameclock()
gameClock.stopGameclock()
startstop.setImage(UIImage(named: "start.png"), forState: UIControlState.Normal)
startstopPushed = false
}
I 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
override func viewDidLoad() {
super.viewDidLoad()
gameclockLabel.text = "00:00"
}
var startstopPushed: Bool = false
var gameClock = GameClock()
#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
}
}

Related Links

How to calculate the distance between my current location and locations populated in a JSON File
UISplitViewController display wrong ViewController on launch
Uber SDK in swift 3 and xcode 8 compatible
SIGABRT error on ios simulator
Drawing rotated text on an image is offset slightly on the x axis of CGContext iOS 10 Swift 3
Can't Access the Albums of Currently Login Facebook User - Swift
I want to store json data and use it when require ios
Xcode object type popup equivalent in AppCode?
UITableView dynamic cells and static cells with container view
Deallocate UIViewController after Segue
difference between normal profile and provisioning profile iOS
use audioQueue Record Audio but missing data
How to segue to a new ViewController from infowindow of Google Maps in Swift?
Xcode: NSMutableArray not able to have more than 3 entries
IOS perform segue from tab bar item
iOS - tabBar item inset doesnt work

Categories

HOME
codeigniter
matlab
odoo-10
robotframework
jsessionid
prebuild
weight
chronicle
antlr
stripe-payments
angular-mdl
calayer
cobol
jquery-jtable
avr
apex
plots.jl
raspberry-pi2
media-source
aikau
urlrewriter.net
sax
iteration
naturallyspeaking
mathdotnet
typemock-isolator
sql-server-2014-express
cloudinary
google-shared-contacts
spring-websocket
blockui
inria-spoon
hamcrest
sieve-of-eratosthenes
gradient-descent
phing
extjs4
ibm-wcm
worldpay
automata-theory
hostname
backwards-compatibility
free-diameter
maven-jetty-plugin
ase
invalidate
powerpc
simplesamlphp
mrtg
orchestrate
billing
itertools
gpt
findall
singlepage
email-notifications
android-sdk-tools
informatica-cloud
building
xendesktop
agents-jade
activity-diagram
4d
menustrip
jongo
highslide
jquery-load
laravel-forge
jedi
post-processor
linq2db
android-gpuimageview
polygons
perfview
bonfire
easynetq
sendto
bessel-functions
globus-toolkit
spread-toolkit
youtrack-api
srp
pydatalog
ramdisk
colormatrix
nsusernotificationcenter
broadcom
qdebug
xhtml-transitional
geometry-surface
wpf-4.0
51degrees
documentviewer
code-structure
ribbon-control
letter-spacing
boost-gil
facebook-authentication
alivepdf
jquery-1.3.2
xoom
dynamic-websites
gedcom

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App