2

さて、このコードはかなり基本的なものです。ユーザーはテキストボックスに答えを入力し、それが「1 番目 + 2 番目」に等しい場合、ポイントを獲得します。次に、次の数学の問題に答えるために 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;
    }
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 に答える