所以我试图进行倒计时,当它完成游戏结束时。这是我的代码:
-(void)Movement667{
loadinglabel.text = [NSString stringWithFormat:@"Go!"];;
end =[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(Movement999)userInfo:nil repeats:YES];
}
-(void)Movement999{
if (gametime > 0){
gametime = gametime - 1;
gametimelabel.text = [NSString stringWithFormat:@"%i", gametime];
}else{
smallrock6.hidden = YES;
endlabel.hidden = NO;
highscore.hidden = NO;
highscoreannouncer.hidden = NO;
highscorebackground.hidden = NO;
highscore.text = [NSString stringWithFormat:@"%i", score];
}
}
我第一次玩它时一切正常,它每秒倒计时。当我第二次播放它等等它开始正常然后它以更大的模式倒计时,即2,4,5等。有谁知道为什么?
答案 0 :(得分:2)
游戏完成后,请不要忘记使
无效[end invalidate];
将此代码放在Movement999的else语句中。 它会阻止接收器再次发射。然后你可以为新游戏重新启动计时器。
答案 1 :(得分:2)
这是因为你永远不会停止计时器。那么当你重置时间并创建一个新的计时器时,会有两个计时器同时运行(选择器每秒调用两次),然后是三个,四个,等等。尝试将计时器保留在一个属性中更改代码如下:
@property (strong, nonatomic) NSTimer *myTimer;//ADDDED
-(void)Movement667{
loadinglabel.text = [NSString stringWithFormat:@"Go!"];;
self.myTimer =[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(Movement999)userInfo:nil repeats:YES];//CHANGED
}
-(void)Movement999{
if (gametime > 0){
gametime = gametime - 1;
gametimelabel.text = [NSString stringWithFormat:@"%i", gametime];
}else{
[self.myTimer invalidate];//ADDED
smallrock6.hidden = YES;
endlabel.hidden = NO;
highscore.hidden = NO;
highscoreannouncer.hidden = NO;
highscorebackground.hidden = NO;
highscore.text = [NSString stringWithFormat:@"%i", score];
}
}
已添加:如果您需要在用完之前中断游戏,则应确保在这种情况下调用[self.myTimer invalidate]。
已添加:如果您想确保在ViewController关闭屏幕时计时器也无效,我建议在viewDidDisappear中使计时器无效:
-(void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[self.myTimer invalidate];
}