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

iPad crash with Foundation
Reorder Uitableview with Parse Objects?
Running Xamarin.iOS tabbed application in VS2015
How to change presentViewController Transition animation
Overriding 'finished' in asynchronous NSOperation
Change parameter inside dispatch_async from main thread
fb ios sdk 4.5 crashes in iOS7
How to get last frame from video?
Share content on an iOS native app via messages or email with long enough trial
UIPaveViewController with page indicator overlaying content
UITableView in Storyboard hidden first cell when it back it will OK ? why?
iOS: ActionSheetStringPicker successAction: wrong selection
Swift calling delegate from didSet
iOS 8 and segues throwing unexpected exception
<TextInput keyboardType=“numeric”/> is not working in react native
UITableViewController scrollViewDidScroll: not called during cell removal

Categories

HOME
dom
module
ssl-certificate
auth0
apt-get
graylog2
garbage-collection
geolocation
runtime-error
open-source
box
httpbuilder-ng
netbeans-8
cross-domain
tcplistener
android-vision
pymc3
sparkpost
openmodelica
editor
afnetworking-2
orientdb-2.1
thrift
opencms
spark-graphx
rgdal
jqplot
symbolic-math
apache-httpcomponents
pdfa
trial
f2py
temp
clappr
apache-commons-httpclient
stomp
scom
cloudinary
html-select
seh
pdfstamper
gradient-descent
executorservice
bits
transpose
caldroid
spring-saml
runc
bem
compass-lucene
firedac
ulimit
mergesort
rtems
gretl
pulseaudio
mobile-browser
sql-mode
mrtg
koala-framework
canopen
mashery
mspgcc
billing
a-star
angular-directive
agile-processes
proc
jsbin
agents-jade
activity-diagram
singly-linked-list
activemodel
pypyodbc
isapi-rewrite
mutation
viewengine
android-popupwindow
schematiq
relaxng
clientid
ssha
uikeyboard
database-tuning-advisor
tun
gulp-rename
tabbar
pegkit
smarty2
antiforgerytoken
repaint
imaging
prettyfaces
concurrentdictionary
globus-toolkit
custom-titlebar
validform
memoization
firebird2.1
chromeless
neventstore
impdp
src
layout-manager
dependency-walker
wescheme
doophp
arr
android-screen
stumbleupon
program-files
dired
soapheader
spquery
indextank
scramble
anemic-domain-model
nhaml
versant-vod
plumtree

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