NSTimer如何修复我的代码

时间:2012-06-26 10:17:33

标签: iphone ios5 xcode4.3

如果timer1Elapsed完成倒数计时器然后转到下一个timer2Elapsed,在完成倒计时后返回到timer1Elapsed倒计时,如何写代码,依此类推重复进程5次。在条件A和B具有固定时间似乎(A - > B - > A - > B ... 5次),只是说A计数1分钟而B计数30秒。请帮忙,请不要输错,因为我是初学者。如果我的代码错了,请纠正我。请慷慨。

- (void) timer2Elapsed:(id)timer
{
    ...

    if (remainingTime <= 0)
    {
        [timer invalidate];
        [NSTimer scheduledTimerWithTimeInterval:0.99 target:self selector:@selector(timer3Elapsed:) userInfo:nil repeats:YES];
    }

    myDisplay.text = [NSString stringWithFormat:@"%d : %d : %d", hour , minute, second];
}

- (void) timer1Elapsed:(id)timer
{
    ...

    if (remainingTime <= 0)
    {
        [timer invalidate];
        [NSTimer scheduledTimerWithTimeInterval:0.99 target:self selector:@selector(timer2Elapsed:) userInfo:nil repeats:YES];
    }

    myDisplay.text = [NSString stringWithFormat:@"%d : %d : %d", hour , minute, second];
}

这是我的按钮

- (IBAction)startBtn:(id)sender {
        [NSTimer scheduledTimerWithTimeInterval:0.99 target:self selector:@selector(timer1Elapsed:) userInfo:nil repeats:YES];
}

1 个答案:

答案 0 :(得分:1)

如果您需要一个计时器来呼叫另一个计时器,您可以使用以下代码

+ (void) timer2Elapsed:(id)timer
{
    static int numberOfTimes = 0;
    if(numberOfTimes >= 5)
    {
        numberOfTimes = 0;
        return;
    }
    numberOfTimes ++;

    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timer1Elapsed:) userInfo:nil repeats:NO];
}

- (void) timer1Elapsed:(id)timer
{
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timer2Elapsed:) userInfo:nil repeats:NO];
}

- (void)startTimers
{
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timer1Elapsed:) userInfo:nil repeats:NO];
}