Я пытаюсь использовать таймер, чтобы отслеживать время в игре. Вот код для таймера. Почему каждый раз, когда я перезагружаю игру из главного меню, таймер запускается почти вдвое быстрее. Это потому, что я не отменяю таймер, прежде чем я уйду. Я пытался сделать таймер недействительным, но он выдает ошибку exc_bad access
-(void) StartTimer {
TotalSeconds = 0;
GameCenterTotalSeconds = 0;
timeSec = 0;
timeMin = 0;
timer = [[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES]retain];
//[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
//Event called every time the NSTimer ticks.
- (void)timerTick:(NSTimer*) timer {
TotalSeconds++;
GameCenterTotalSeconds= GameCenterTotalSeconds + .1;
timeSec = timeSec + .1;
if (timeSec >= 60)
{
timeSec = 00;
timeMin++;
}
//Format the string 00:00
NSString* timeNow = [NSString stringWithFormat:@"Time: %02d:%.1f", timeMin, timeSec];
//Display on your label
timeLabel.text = timeNow;
}
//Call this to stop the timer event(could use as a 'Pause' or 'Reset')
- (void) StopTimer {
[timer invalidate];
//Since we reset here, and timerTick won't update your label again, we need to refresh it again.
//Format the string in 00:00
NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
//Display on your label
timeLabel.text = timeNow;
}