I’m creating a simple pong game..
right now i wanted to set a timer which will stop after i loose and save the value to high score possibly, but even though i managed to set up the timer and set him on, it seem to not want to stop.
i was implementing it using this tutorial:
http://www.apptite.be/tutorial_ios_stopwatch.php
Right now my code looks like this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (StavHry == StavHryPozastaven) {
TapToBegin.hidden = YES;
StavHry = StavHryAktivni;
} else if (StavHry == StavHryAktivni) {
[self touchesMoved:touches withEvent:event];
}
startDate = [NSDate date];
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target:self selector:@selector(updateTimer)userInfo:nil repeats:YES];
}
- (void)updateTimer
{
static NSInteger counter = 0;
StopWatchLabel.text = [NSString stringWithFormat:@"Counter: %i", counter++];
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
StopWatchLabel.text = timeString;
}
i set on the timer when i tap on TapToBegin label..
but when i loose or win the timer just keeps running even though i used invalidate in the function before setting off a new game.. (when i start a new game it resets)
-(void)reset:(BOOL) novahra { //funkce reset
self.StavHry = StavHryPozastaven;
mic.center = self.view.center;
if(novahra) {
if(skore_hrac_hodnota < skore_pc_hodnota){
TapToBegin.text = @"Protivnik Vyhrál, smůla!";
[stopWatchTimer invalidate];
} else {
TapToBegin.text = @"Vyhráls! Gratulujem!";
[stopWatchTimer invalidate];
}
skore_hrac_hodnota = 0;
skore_pc_hodnota = 0;
} else {
self.StavHry = StavHryAktivni;
//TapToBegin.text = @"Pokračuj!";
}
skore_hrac.text = [NSString stringWithFormat:@"%d", skore_hrac_hodnota];
skore_pc.text = [NSString stringWithFormat:@"%d", skore_pc_hodnota];
}
i know that the tutorial shows more lines of code for it’s stop action, but i tried more options i gave it everything it has, but i think this is the only line which stops the timer so it should work. but it doesn’t.
please help, i have a due on monday to finish this, so I’m freaking out a little.
What happens if
touchesBegan:is called more than once andreset:is not called in between? if it can happen you probably leak a timer that will continue to call yourupdateTimermethod.Im a bit surprised if the code you posted works as the timer method should take an argument. That is change your timer selector to
@selector(updateTimer:)and then change to the method to- (void)updateTimer:(NSTimer *)timer.