我想用NSTimer做一个秒表.

我给出了以下代码:

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

它在几毫秒内不工作.这需要超过1毫秒.

推荐答案

不要那样用NSTimer.NSTimer通常用于在某个时间间隔触发 Select 器.它的精度不高,不适合你想做的事情.

你想要的是High resolution timer级(使用NSDate):

Output:

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

Main:

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]);

Edit:增加了-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

Objective-c相关问答推荐

UICollectionView:一行或一列

使用自动布局自定义纵横比

ARC下归零弱引用的集合

来自 NSString 的 NSJSONSerialization

如何在使用 React Native 时实现 SSL 证书固定

应用程序内部的Gift App

iOS6:supportedInterfaceOrientations 不起作用(被调用但界面仍然旋转)

如何在Objective C(NSRegularExpression)中编写正则表达式?

如何在 iOS 7 启动期间更改状态栏样式

在 NSArray 中查找最大数值

Modal segue,导航栏消失

滑动删除单元格导致 tableView 标题随单元格移动

自定义 colored颜色 我的 UIActivityIndi​​catorView

@class 在 Objective-C 中做了什么?

使用 respondsToSelector 时 suppress '...' is deprecated

NSNumber 和 NSInteger 有什么区别?

如何将 UITableView 滚动到特定位置

xcode 5.1 中的 Arm64 架构

使用正则表达式查找/替换 NSString 中的子字符串

Objective-C:如何向 NSURL 添加查询参数?