Ios 如何使NSTimer在xcode上保持一致

Ios 如何使NSTimer在xcode上保持一致,ios,xcode,Ios,Xcode,我正在做一个游戏,想用计时器来倒计时,就像在Bejeweled上看到的一样。我知道我必须将NSTimer放入nsrunlop以使其工作,因为NSTimer不准确。已经尝试了以下方法,但仍然不起作用。请帮忙 #import ... NSTimer *_gameTimer; int secondsLeft; //some code //called countdownTimer using [self countdownTimer]; - (void)countdownTimer { _

我正在做一个游戏,想用计时器来倒计时,就像在Bejeweled上看到的一样。我知道我必须将NSTimer放入nsrunlop以使其工作,因为NSTimer不准确。已经尝试了以下方法,但仍然不起作用。请帮忙

#import ...
NSTimer *_gameTimer;
int secondsLeft;

//some code
//called countdownTimer using [self countdownTimer];

- (void)countdownTimer
{
    _gameTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
    NSRunLoop *gameRun = [NSRunLoop currentRunLoop];
    [gameRun addTimer:_gameTimer forMode:NSDefaultRunLoopMode];
}

- (void)updateTime:(NSTimer *)timer
{
     if (secondsLeft>0 && !_gameOver) {
     _timerLabel.text = [NSString stringWithFormat:@"Time left: %ds", secondsLeft];
     secondsLeft--;
} else if (secondsLeft==0 && !_gameOver) {
     // Invalidate timer
     [timer invalidate];
     [self timerExpire];
     }
}

- (void)timerExpire
{
    // Gameover
    [self gameOver];

    [_gameTimer invalidate];
    _gameTimer = nil;
}

NSTimer需要是一个局部变量,因此循环中只能有一个对象实例。这是密码

- (void)countdownTimer
{
    NSTimer *_gameTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
    NSRunLoop *gameRun = [NSRunLoop currentRunLoop];
    [gameRun addTimer:_gameTimer forMode:NSDefaultRunLoopMode];

     if (secondsLeft==0 || _gameOver) {
        [_gameTimer invalidate];
        _gameTimer = nil;
    }
}

- (void)updateTime:(NSTimer *)timer
{
    if (secondsLeft>0 && !_gameOver) {
        _timerLabel.text = [NSString stringWithFormat:@"Time left: %ds", secondsLeft];
        secondsLeft--;
    } else if (secondsLeft==0 || _gameOver) {
        // Invalidate timer
        [timer invalidate];
        [self timerExpire];
}

- (void)timerExpire
{
    // Gameover
    [self gameOver];
}

NSTimer*\u游戏计时器;这是全球性的。为什么?我用不同的方法叫它countdownTimer和timerExpire,所以它是全球性的。。有更好的方法吗?是的,它需要一个实例变量。使用全局变量意味着该对象只能有一个实例。这很糟糕。那么这意味着我应该在倒计时中启动NSTimer,然后在secondsLeft==0时用相同的方法使其无效?好的,我尝试过了,现在它可以工作了。我会把答案贴上去。非常感谢!