gpt4 book ai didi

iphone - 停止 NSTimer

转载 作者:行者123 更新时间:2023-12-03 20:26:57 26 4
gpt4 key购买 nike

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

问题是,当用户连续正确地解决多个问题时,“doCalculation”会运行多次,然后我会同时启动多个计时器。这真的开始搞砸游戏。

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

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

最佳答案

我会将 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;
}

关于iphone - 停止 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1732904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com