【问题标题】:NSTimer how to fix my codeNSTimer 如何修复我的代码
【发布时间】:2012-06-26 10:17:32
【问题描述】:

如何编写代码如果 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];
}

【问题讨论】:

    标签: iphone ios5 xcode4.3


    【解决方案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];
    }
    

    【讨论】:

    • 怎么用for循环?只说5次重复?
    • 在你的类中添加一个计数器变量,每次调用定时器都会增加,当它达到5时,不要安排新的定时器
    • @Piyo 检查更新的答案,它显示了如何使用静态整数将其限制为 5 次
    • 您的 + (void) timer2Elapsed:(id)timer 错误。以及为什么要回到 timer1Elapsed 而不是 startTimers。我有 2 个计时器过程要在这里循环。我认为这里的人还没有像我一样制作计时器,所以无法理解我的问题。
    • 我不明白你想要获得什么?您是要刷新视图还是什么?
    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 2015-10-02
    • 2019-11-25
    • 2018-11-11
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多