在Objective-C中我的计时器有毫秒

问题描述 投票:0回答:1

我正在使用youtube教程做秒表。问题是我在计时器中需要毫秒,但教程只显示如何获得秒和分钟。我想显示毫秒显示的分钟和秒,但我不知道该怎么做。

如何使用此代码获取毫秒?

@implementation ViewController {

    bool start;
    NSTimeInterval time;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.display.text = @"0:00";
    start = false;
}

- (void) update {

    if ( start == false ) {
        return;
    }
    NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
    NSTimeInterval elapsedTime = currentTime - time;

    int minutes = (int) (elapsedTime / 60.0);

    int seconds = (int) (elapsedTime = elapsedTime - (minutes * 60));

    self.display.text = [NSString stringWithFormat:@"%u:%02u", minutes, seconds];

    [self performSelector:@selector(update) withObject:self afterDelay:0.1];
}
objective-c xcode timer
1个回答
0
投票

根据文档,“NSTimeInterval总是以秒为单位指定;它在10,000年的范围内产生亚毫秒精度。”因此,您需要做的就是从elapsedTime变量中提取毫秒,然后再次格式化文本,使其包含毫秒数。它可能看起来像这样:

NSInteger time = (NSInteger)elapsedTime;
NSInteger milliseconds = (NSInteger)((elapsedTime % 1) * 1000);
NSInteger seconds = time % 60;
NSInteger minutes = (time / 60) % 60;
//if you wanted hours, you could do that as well
//NSInteger hours = (time / 3600);
self.display.text = [NSString stringWithFormat: "%ld:%ld.%ld", (long)minutes, (long)seconds, (long)milliseconds];
© www.soinside.com 2019 - 2024. All rights reserved.