【问题标题】:Stopwatch counting in powers of 2秒表以 2 的幂计数
【发布时间】:2013-08-24 14:41:33
【问题描述】:

我正在 Objective-C 中制作秒表:

- (void)stopwatch
{
    NSInteger hourInt = [hourLabel.text intValue];
    NSInteger minuteInt = [minuteLabel.text intValue];
    NSInteger secondInt = [secondLabel.text intValue];

    if (secondInt == 59) {
        secondInt = 0;
        if (minuteInt == 59) {
            minuteInt = 0;
            if (hourInt == 23) {
                hourInt = 0;
            } else {
                hourInt += 1;
            }
        } else {
            minuteInt += 1;
        }
    } else {
        secondInt += 1;
    }

    NSString *hourString = [NSString stringWithFormat:@"%d", hourInt];
    NSString *minuteString = [NSString stringWithFormat:@"%d", minuteInt];
    NSString *secondString = [NSString stringWithFormat:@"%d", secondInt];

    hourLabel.text = hourString;
    minuteLabel.text = minuteString;
    secondLabel.text = secondString;

    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES];
}

如果您想知道,秒表有三个单独的标签,分别是小时、分钟和秒。但是,不是按 1 计数,而是按 2、4、8、16 等计数。

此外,代码的另一个问题(非常小的问题)是它不会将所有数字显示为两位数。例如,它将时间显示为 0:0:1,而不是 00:00:01。

非常感谢任何帮助!我应该补充一点,我是 Objective-C 的新手,所以尽量保持简单,谢谢!!

【问题讨论】:

    标签: ios nstimer


    【解决方案1】:

    如果您在每次迭代中安排计时器,请不要使用repeats:YES

    您在每次迭代时都生成一个计时器,并且计时器已经在重复,从而导致计时器呈指数增长(从而导致对stopwatch 的方法调用)。

    将定时器实例化为:

    [NSTimer scheduledTimerWithTimeInterval:1.0f
                                     target:self
                                   selector:@selector(stopwatch)
                                   userInfo:nil
                                    repeats:NO];
    

    或在stopwatch 方法之外启动它

    对于第二个问题,只需使用正确的格式字符串。

    NSString *hourString = [NSString stringWithFormat:@"%02d", hourInt];
    NSString *minuteString = [NSString stringWithFormat:@"%02d", minuteInt];
    NSString *secondString = [NSString stringWithFormat:@"%02d", secondInt];
    

    %02d 将打印一个用0s 填充的十进制数,长度为 2,这正是您想要的。

    (source)

    【讨论】:

    • 这真是太棒了。如此简单且非常有帮助的答案;解决了所有的问题!非常感谢!
    【解决方案2】:

    对于第一个问题,而不是为每个调用创建一个计时器实例。删除该行

     [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES];
    

    来自函数秒表。

    将您对函数秒表的调用替换为上面的行。即替换

    [self stopwatch]
    

     [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES];
    

    【讨论】:

      猜你喜欢
      • 2014-02-21
      • 2011-05-05
      • 2013-03-09
      • 2011-10-27
      • 1970-01-01
      • 2016-06-11
      • 2018-06-30
      • 1970-01-01
      • 2017-02-03
      相关资源
      最近更新 更多