简体   繁体   English

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

[英]Objective C: Remotely invalidate a timer

How do I invalidate a timer in one method when another method is called? 如何在调用另一个方法时使一个方法中的计时器无效? Basically when tapFig is called, I want it to send a message to moveStickFig to invalidate the 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];
}

I think you need a flag in moveStickFig that sets to true when tapFig is called. 我认为你需要在一个标志moveStickFig ,设置为true时tapFig被调用。

-(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;
    // ......
}

Note: Usually, you will set the timer to call a function repeatedly at a fixed frames per second. 注意:通常,您将设置计时器以每秒固定帧的速度重复调用函数。 The timer does the job of calling it at that rate. 计时器以该速率进行调用。 There is no need of passing timer instance repeatedly. 无需重复传递计时器实例。 If that is what you want, then OK. 如果那是您想要的,那么确定。 However, if you need your game logic to be continued, you need to reset the isTimerInvalidateSet to false. Hope this helps ! 希望这可以帮助 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM