【问题标题】:What is wrong with my countdown timer method?我的倒计时方法有什么问题?
【发布时间】:2013-07-30 18:08:34
【问题描述】:

试图从给定的 NSTimeInterval 中创建倒数计时器,标签似乎没有更新。

- (IBAction)startTimer:(id)sender{
      timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}

- (void)timerAction:(NSTimer *)t {

    if(testTask.timeInterval == 0){
        if (self.timer){
            [self timerExpired];
            [self.timer invalidate];
            self.timer = nil;
        }

        else {
            testTask.timeInterval--;
        }
    }

    NSUInteger seconds = (NSUInteger)round(testTask.timeInterval);
    NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
                        seconds / 3600, (seconds / 60) % 60, seconds % 60];
    timerLabel.text = string;
}

【问题讨论】:

  • testTask 由用户指定,我一直在以 10 秒的时间间隔测试它。它显示了 10 秒,但没有显示任何变化。
  • 而且时间间隔实际上从未减少
  • 你是否在 timerAction 方法中设置了断点?它真的被调用了吗?
  • 刚试过。是的,它被调用了
  • 我会检查或 NSLog 秒值和字符串值。您还应该在 else 部分中添加一个断点,以查看是否正在发生递减。

标签: iphone ios objective-c nstimer countdown


【解决方案1】:

问题是,您正在减少 testTask.timeInterval 内的 if(testTask.timeInterval == 0) ,此条件永远不会计算为真(因为您将其设置为 10)。这就是标签没有变化的原因。

您需要将 else case 放在第一个 if 语句之后(目前您将它放在第二个 if 语句下)。

你需要这样写你的方法:

-(void)timerAction:(NSTimer *)t
{
        if(testTask.timeInterval == 0)
        {
            if (self.timer)
            {
                [self timerExpired];
                [self.timer invalidate];
                self.timer = nil;
            } 
       }
       else
       {
            testTask.timeInterval--;
       }
       NSUInteger seconds = (NSUInteger)round(testTask.timeInterval);
       NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
                        seconds / 3600, (seconds / 60) % 60, seconds % 60];
       timerLabel.text = string;
}

【讨论】:

  • @user2533646:我想你需要喝杯咖啡 :) 快乐编码 :)
【解决方案2】:

我相信您的 if 语句嵌套不正确。像这样将你的 else 语句移动到最外面的“if”。

    if(testTask.timeInterval == 0){
        if (self.timer){
            [self timerExpired];
            [self.timer invalidate];
            self.timer = nil;
        }
    } else {
        testTask.timeInterval--;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多