调用时定时器不启动

时间:2014-07-20 05:45:55

标签: xcode timer nstimer nstimeinterval

按下按钮时,计时器未启动。我正在尝试创建一个应用程序,无论何时按下按钮,计时器启动,在某个时刻计时器停止,然后在我离开的地方继续。

    -(IBAction)start:(id)sender{
    [self startTimer];

    [self counterStart];

}

- (void)startTimer
{
    homeButton.hidden=YES;
    gameButton.hidden=YES;


    NSTimeInterval timeInterval = 20.0f;

    // Create a timer. Adjust the elapsed time.
    if (counter == 0)
    timer = [NSTimer scheduledTimerWithTimeInterval:(timeInterval - _elapsedTime)
                                              target:self
                                            selector:@selector(timerFireMethod:)
                                            userInfo:nil
                                             repeats:YES];
    // Save the start date.
    startDate = [NSDate date];
}


- (void)timerFireMethod:(NSTimer *)theTimer
{
    // Clean.
    [timer invalidate];
    timer = nil;
    _elapsedTime = 0.0;

    [self startTimer];

    // Additional handling.
}


- (void)pauseTimer
{
    // Clean.
    [_timer invalidate];
    _timer = nil;

    // Save the elapsed time.
    _elapsedTime = [[NSDate date] timeIntervalSinceDate:_startDate];
}

1 个答案:

答案 0 :(得分:0)

我有同样的问题,我尝试使用“timerWithTimeInterval”而不是“scheduledTimerWithTimeInterval”,它开始工作,试试这个 -

NSTimer *timer = [NSTimer timerWithTimeInterval:(timeInterval - _elapsedTime) target:self selector:@selector(timerFireMethod) userInfo:nil repeats:YES];
[timer fire];