【问题标题】:Having milliseconds in my timer in Objective-C在 Objective-C 中的计时器中有毫秒
【发布时间】:2015-03-30 16:10:11
【问题描述】:

我正在使用 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】:

    根据文档,“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];
    

    【讨论】:

    • 不客气。很高兴它有帮助。如果这对你有用,当你有机会时,你能接受这个作为答案吗? (绿色复选标记)。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多