停止NSTimer

时间:2009-11-14 01:23:07

标签: iphone objective-c nstimer

好的,所以,这段代码非常基础。用户将答案输入到文本框中,如果它等于“第一+第二”,则他们得到一个点。然后,他们有5秒钟来回答下一个数学问题。如果他们这样做,则再次运行“doCalculation”函数,他们得到另一个点。如果他们不这样做,那么就会运行“onTimer”功能,然后就会对风扇产生影响。

问题是,当用户连续多次出现问题时,“doCalculation”会多次运行,然后我会同时运行多个计时器。这真的开始搞砸游戏。

我需要停止计时器。显然使用“无效”但我不知道在哪里。我不能在计时器开始之前使计时器无效,所以...那是什么?

我不确定如何做的另一种选择,如果每次问题得到解决时,只需将计时器设置为5秒而不是创建新计时器。但是如何判断定时器是否已经创建?我不确定最佳的行动方案或语法。想法?

非常感谢!

- (IBAction)doCalculation:(id)sender
{
    NSInteger numAnswer = [answer.text intValue];
    if ( numAnswer == first + second) {
        numAnswered++;
        NSString *numberAnsweredCorrectly = [[NSString alloc] initWithFormat:@"%d", numAnswered];
        numCorrectlyAnswered.text = numberAnsweredCorrectly;
        answer.text = @"";

        NSTimer *mathTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];     

        //Set the variables to two HUGE numbers, so they can't keep plugging in the same answer

        first = arc4random() % 10;
        second = arc4random() % 10;

        NSString *firstString = [[NSString alloc] initWithFormat:@"%d", first];
        NSString *secondString = [[NSString alloc] initWithFormat:@"%d", second];

        firstNumber.text = firstString;
        secondNumber.text = secondString;
    }

2 个答案:

答案 0 :(得分:6)

我会将mathTimer移动到您的类标题中:

//inside your .f file:
@interface YourClassNAme : YourSuperClassesName {
    NSTimer *mathTimer
}


@property (nonatomic, retain) NSTimer *mathTimer;

//inside your .m:
@implementation YourClassNAme 
@synthesize mathTimer;

-(void) dealloc {
   //Nil out [release] the property
   self.mathTimer = nil;
   [super dealloc];
}

并通过属性更改您的方法以访问计时器:

- (IBAction)doCalculation:(id)sender
{
    NSInteger numAnswer = [answer.text intValue];
    if ( numAnswer == first + second) {
        numAnswered++;
        NSString *numberAnsweredCorrectly = [[NSString alloc] initWithFormat:@"%d", numAnswered];
        numCorrectlyAnswered.text = numberAnsweredCorrectly;
        answer.text     = @"";

        [self.mathTimer invalidate];  //invalidate the old timer if it exists
        self.mathTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];             

        //Set the variables to two HUGE numbers, so they can't keep plugging in the same answer

        first = arc4random() % 10;
        second = arc4random() % 10;

        NSString *firstString = [[NSString alloc] initWithFormat:@"%d", first];
        NSString *secondString = [[NSString alloc] initWithFormat:@"%d", second];

        firstNumber.text = firstString;
        secondNumber.text = secondString;
    }

答案 1 :(得分:1)

如果您正在制作游戏,则应使用游戏循环,在该游戏循环中更新游戏。然后你可以在时间结束后查看结果。你将只有1个连续计时器来处理。