当调用另一种方法时,如何使一种方法中的计时器无效?基本上,当调用 tapFig
时,我希望它向 moveStickFig
发送一条消息以使计时器无效
-(void) moveStickFig:(NSTimer *)timer {
UIButton *stick = (UIButton *)timer.userInfo;
CGPoint oldPosition = stick.center;
stick.center = CGPointMake(oldPosition.x + 1 , oldPosition.y);
if (oldPosition.x == 900) {
[stick removeFromSuperview];
healthCount--;
NSLog(@"%d", healthCount);
[healthBar setImage:[UIImage imageNamed:[NSString stringWithFormat:@"health%d.png",healthCount]]];
}
}
-(void) tapFig:(id)sender {
UIButton *stick = (UIButton *)sender;
count++;
score.text = [NSString stringWithFormat:@"%d", count];
[stick removeFromSuperview];
[stick release];
}
最佳答案
我认为您需要在 moveStickFig
中设置一个标志,在调用 tapFig
时将其设置为 true。
-(void) moveStickFig:(NSTimer *)timer
{
if( isTimerInvalidateSet )
{
[ self timer:invalidate ];
return;
}
// ......
}
// you need to pass the same timer instance to `tapFig` that you earlier passed to `moveStickFig`.
-(void) tapFig:(id)sender
{
isTimerInvalidateSet = true;
[ self moveStickFig:theTimerInstance ] ; // theTimerInstance is same as earlier you passed to `moveStickFig`
isTimerInvalidateSet = false;
// ......
}
注意:通常,您将设置计时器以每秒固定的帧数重复调用函数。计时器负责以该速率调用它。无需重复传递计时器实例。如果这就是您想要的,那么好吧。 但是,如果您需要继续游戏逻辑,则需要将 isTimerInvalidateSet 重置为 false。
希望这会有所帮助!
关于objective-c - Objective-C : Remotely invalidate a timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4838159/