NSTimer越来越快

App*_*per 2 objective-c nstimer

我试图使用计时器来跟踪游戏中的时间.这是计时器的代码.为什么每次我从主菜单重新启动游戏时计时器几乎快两倍.是因为我在退出之前没有使计时器失效.我试图使计时器无效,但它只是给出错误exc_bad访问权限

-(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;
}
Run Code Online (Sandbox Code Playgroud)

hig*_*ted 5

如果在退出之前没有使计时器失效,则下次启动时会创建第二个计时器,因此事件的触发次数是常常的两倍.