秒表以 2 的幂计数 [英] Stopwatch counting in powers of 2

查看:58
本文介绍了秒表以 2 的幂计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Objective-C 制作秒表:

I am making a stopwatch in 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 等那样计数.

The stopwatch has three separate labels, if you were wondering, for hours, minutes and seconds. However, instead on counting by 1, it counts like 2, 4, 8, 16, etc.

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

Also, another issue with the code (quite a minor one) is that it doesn't display all numbers as two digits. For example it's shows the time as 0:0:1, not 00:00:01.

非常感谢任何帮助!我应该补充一点,我对 Objective-C 真的很陌生,所以尽可能简单,谢谢!!

Any help is really appreciated! I should add that I am really new to Objective-C so keep it as simple as possible, thank you!!

推荐答案

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

Don't use repeats:YES if you schedule the timer at every iteration.

您在每次迭代时生成一个计时器,而该计时器已经在重复,导致计时器呈指数级增长(从而导致对 秒表 的方法调用).

You're spawning one timer at every iteration and the timer is already repeating, resulting in an exponential growth of timers (and consequently of method calls to stopwatch).

将计时器实例更改为:

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

或在秒表方法外启动

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

For the second issue simply use a proper format string.

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

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

%02d will print a decimal number padding it with 0s up to length 2, which is precisely what you want.

(来源)

这篇关于秒表以 2 的幂计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆