objective-c - Objective-C : Remotely invalidate a timer

标签 objective-c ios methods timer

当调用另一种方法时,如何使一种方法中的计时器无效?基本上,当调用 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/

相关文章:

objective-c - 移动 CGPathCreateMutable() 以便路径保持不变?

ios - 有没有办法在发生某些事情后停止 touches 方法?

iOS更改标签的行数

java - 使用更少的代码从同一类调用多个对象的方法的方法

Objective-C 类方法 : dot syntax and 'class property'

ios - Swift 3 扩展返回 "has no member"错误

ios - 在 UITableView 中拖放整个部分而不是单行

ios - 获取图像的像素值并裁剪图像的黑色部分 : Objective C

Java Noob 创建自定义方法来打印数组并计算持续时间

python - 如何确定实例方法对应的类?