Objective-C:如何阻止NSTimer?

时间:2014-07-22 03:02:19

标签: xcode

每当我尝试[myTimer invalidate]时,我将如何停止计时器;我收到了错误。

我的计时器:

    NSTimer *MyTimer;
MyTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0
                                         target: self
                                       selector: @selector(handleTimer)
                                       userInfo: nil
                                        repeats: YES];

这是我为计时器设置的if语句。

-(void)handleTimer{

if (count >= 0) {
    [secondsLeft setText:[NSString stringWithFormat:@"%ld",(long)count]]; //displays current value of count to UI
    count--; //Incrementally decreases count
} else if(count <= 0) { //if the timer runs out then...
self.secondsLeft.text = @"Times's Up!";
    [answerButtonOutlet setEnabled:NO];
    self.secondsLeftToAnswer.text = @"Answer is 30";
} else if([self.secondsLeftToAnswer.text isEqual: @"Correct!"]) { //else if statement if user gets answer Correct.
    [myTimer invalidate]; // error occurs here. "Unknown receiver 'myTimer': did you mean NSTimer?
}

    }

我如何制作它以便我不会在第二个if语句中得到错误?我对编码很陌生,所以我确定它可能非常明显,但我无法理解我的生活。谢谢!

3 个答案:

答案 0 :(得分:1)

NSTimer *MyTimer;

以来

[myTimer invalidate];应为[MyTimer invalidate];

答案 1 :(得分:1)

最好只使用传递给处理程序方法的timer参数。换句话说,在选择器中需要一个额外的冒号来指示处理程序采用参数

selector: @selector(handleTimer:)   // note the colon at the end

然后你的处理程序看起来像这样

-(void)handleTimer:(NSTimer *)theTimer 
{
    ...

    else if([self.secondsLeftToAnswer.text isEqual: @"Correct!"]) { 
        [theTimer invalidate];
    }
}

答案 2 :(得分:0)

你有[myTimer invalidate],你真的应该:

[MyTimer invalidate];
MyTimer = nil;

尝试此更改,让我知道会发生什么。另外,在else if中抛出一个NSLog,以确保它被触发。