如何在Objective-C中编写定时器?

时间:2010-08-19 07:14:55

标签: iphone objective-c timer nsdate nstimer

我正试图用NSTimer进行秒表。

我提供了以下代码:

 nst_Timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(showTime) userInfo:nil repeats:NO];

并且它在几毫秒内无法正常工作。它需要超过1毫秒。

1 个答案:

答案 0 :(得分:88)

请勿以此方式使用NSTimer。 NSTimer通常用于在某个时间间隔触发选择器。它精度不高,不适合你想做的事情。

你想要的是一个高分辨率计时器类(使用NSDate):

<强>输出:

Total time was: 0.002027 milliseconds
Total time was: 0.000002 seconds
Total time was: 0.000000 minutes

主要

Timer *timer = [[Timer alloc] init];

[timer startTimer];
// Do some work
[timer stopTimer];

NSLog(@"Total time was: %lf milliseconds", [timer timeElapsedInMilliseconds]);  
NSLog(@"Total time was: %lf seconds", [timer timeElapsedInSeconds]);
NSLog(@"Total time was: %lf minutes", [timer timeElapsedInMinutes]);

修改:为-timeElapsedInMilliseconds-timeElapsedInMinutes

添加了方法

<强> Timer.h:

#import <Foundation/Foundation.h>

@interface Timer : NSObject {
    NSDate *start;
    NSDate *end;
}

- (void) startTimer;
- (void) stopTimer;
- (double) timeElapsedInSeconds;
- (double) timeElapsedInMilliseconds;
- (double) timeElapsedInMinutes;

@end

<强> Timer.m

#import "Timer.h"

@implementation Timer

- (id) init {
    self = [super init];
    if (self != nil) {
        start = nil;
        end = nil;
    }
    return self;
}

- (void) startTimer {
    start = [NSDate date];
}

- (void) stopTimer {
    end = [NSDate date];
}

- (double) timeElapsedInSeconds {
    return [end timeIntervalSinceDate:start];
}

- (double) timeElapsedInMilliseconds {
    return [self timeElapsedInSeconds] * 1000.0f;
}

- (double) timeElapsedInMinutes {
    return [self timeElapsedInSeconds] / 60.0f;
}

@end