如何为秒表应用添加毫秒?

时间:2014-07-16 22:40:59

标签: ios objective-c nstimer

好的,所以我在这里开始使用本教程中的秒表应用代码http://iphonedev.tv/blog/2013/7/7/getting-started-part-3-adding-a-stopwatch-with-nstimer-and-our-first-class 我喜欢它的设置方式,但我无法弄清楚如何添加百分之一秒,任何人都知道如何做到这一点?

我的ViewController.m文件

#import "ViewController.h"
#import "Foundation/Foundation.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (NSTimer *)createTimer
{
     return [NSTimer scheduledTimerWithTimeInterval:0.01
                                        target:self
                                      selector:@selector(timerTicked:)
                                      userInfo:nil
                                       repeats:YES];
}

- (void)timerTicked:(NSTimer *)timer
{
     _currentTimeInSeconds++;

     self.timeLabel.text = [self formattedTime:_currentTimeInSeconds];
}

- (NSString *)formattedTime:(int)totalSeconds
{
    int hundredths = totalSeconds % 60;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;

    return [NSString stringWithFormat:@"%02d:%02d:%02d.%02d", hours, minutes, seconds, hundredths];
}

- (IBAction)startButtonPressed:(id)sender
{
    if (!_currentTimeInSeconds)
    {
        _currentTimeInSeconds = 0 ;
    }

    if (!_theTimer)
    {
        _theTimer = [self createTimer];
    }
}

- (IBAction)stopButtonPressed:(id)sender
{
    [_theTimer invalidate];
}

- (IBAction)resetButtonPressed:(id)sender
{
    if (_theTimer)
    {
        [_theTimer invalidate];
        _theTimer = [self createTimer];
    }

    _currentTimeInSeconds = 0;

    self.timeLabel.text = [self formattedTime:_currentTimeInSeconds];
}

@end

再次感谢任何可以提供帮助的人!

1 个答案:

答案 0 :(得分:1)

首先,您应该将变量的名称从_currentTimeInSeconds更改为_currentTimeInHundredths(如果需要,还可以更短)。

接下来,您需要更新- (NSString *)formattedTime:(int)totalSeconds方法中的逻辑。尝试这样的事情(将totalSeconds更改为totalHundredths,原因与之前相同)。

int hours = totalHundredths / 360000;
int minutes = (totalHundredths - (hours * 360000)) / 6000;
int seconds = (totalHundredths - (hours * 360000) - (minutes * 6000)) / 100;
int hundredths = totalHundredths - (hours * 360000) - (minutes * 6000) - (seconds * 100);

我还没有测试数字的数学,但它们应该是对的。