为我工作:
AppDelegate.h:
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate> {
NSTimer *_timer;
float _startTime;
}
@property (assign) IBOutlet NSWindow *window;
- (void)flash:(NSTimer *)timer;
@end
AppDelegate.m:
#import "AppDelegate.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
_startTime = 0.0f;
_timer = [NSTimer scheduledTimerWithTimeInterval:1/1000.0f
target:self
selector:@selector(flash:)
userInfo:nil
repeats:YES];
}
- (void)flash:(NSTimer *)timer {
_startTime += 0.001;
NSLog(@"_startTime=%.3f", _startTime);
}
@end
输出:
2013-10-05 10:03:36.330 TimerTest[86869:303] _startTime=0.001
2013-10-05 10:03:36.331 TimerTest[86869:303] _startTime=0.002
2013-10-05 10:03:36.332 TimerTest[86869:303] _startTime=0.003
...
2013-10-05 10:03:37.609 TimerTest[86869:303] _startTime=0.999
2013-10-05 10:03:37.611 TimerTest[86869:303] _startTime=1.000
2013-10-05 10:03:37.612 TimerTest[86869:303] _startTime=1.001
2013-10-05 10:03:37.612 TimerTest[86869:303] _startTime=1.002
但是请注意,您不能保证计时器实际上每 0.001 秒触发一次,因此您应该使用不同的时钟机制计算递增时间,例如将开始时间保存为绝对时间,并在触发方法时测量差异。