2

好的,所以,这段代码非常基本。用户在文本框中输入一个答案,如果它等于“第一+第二”,他们就得一分。然后,他们有 5 秒的时间来回答下一个数学问题。如果他们这样做了,函数“doCalculation”会再次运行,他们会得到另一分。如果他们不这样做,那么函数“onTimer”就会运行,并且会击中风扇。

问题是,当用户连续遇到多个正确的问题时,“doCalculation”会运行多次,然后我有多个计时器同时运行。这真的开始把游戏搞砸了。

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

我不知道该怎么做的另一个选项,如果当你得到正确的问题时它只是将计时器设置回 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;
    }
4

2 回答 2

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;
    }
于 2009-11-14T01:33:33.650 回答
1

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

于 2009-11-14T01:32:03.950 回答