目标C:远程使计时器无效

时间:2011-01-29 17:06:12

标签: 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];
}

1 个答案:

答案 0 :(得分:1)

我认为您需要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;
    // ......
}

注意:通常,您将设置定时器以每秒固定的帧重复调用一个函数。计时器完成以该速率调用它的工作。不需要重复传递计时器实例。如果这是你想要的,那么好的。 However, if you need your game logic to be continued, you need to reset the isTimerInvalidateSet to false.希望这会有所帮助!