Eth*_*ick 2 iphone objective-c nstimer
好的,所以,这段代码非常基础.用户将答案输入到文本框中,如果它等于"第一+第二",则他们得到一个点.然后,他们有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;
}
Run Code Online (Sandbox Code Playgroud)
我会将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];
}
Run Code Online (Sandbox Code Playgroud)
并通过属性更改您的方法以访问计时器:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4060 次 |
| 最近记录: |