2009-11-14 55 views
2

好的,所以這段代碼是非常基本的。用戶在文本框中輸入一個答案,如果它等於「第一+第二」,他們得到一個點。然後,他們有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; 
    } 

回答

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個連續計時器來處理。