好的,所以這段代碼是非常基本的。用戶在文本框中輸入一個答案,如果它等於「第一+第二」,他們得到一個點。然後,他們有5秒鐘的時間來回答下一個數學問題。如果他們這樣做,函數「doCalculation」再次運行,他們得到另一個點。如果他們不這樣做,那麼函數「onTimer」就會運行,並且狗屎撞上風扇。停止NSTimer
問題是,當用戶在一行中遇到多個問題時,「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;
}