我正在尝试使用NSTimer进行秒表监视。

我给出了以下代码:

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

并且它在几毫秒内不起作用。耗时超过1毫秒。

最佳答案

不要那样使用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

关于iphone - 如何在Objective-C中编写计时器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3519562/

10-13 03:55