我只是在做类似的事情。我的代码中有一个名为 timeReamin 的 UILabel。它每秒更新一次,直到达到 0,然后显示警报。我必须警告您,由于计时器与您的 UI 在同一线程上运行,因此您可能会遇到一些抖动。我还没有解决这个问题,但这适用于简单的计时器。这是我正在使用的代码:
- (void)createTimer {
// start timer
gameTimer = [[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain];
[[NSRunLoop currentRunLoop] addTimer:gameTimer forMode:NSDefaultRunLoopMode];
timeCount = 5; // instance variable
}
- (void)timerFired:(NSTimer *)timer {
// update label
if(timeCount == 0){
[self timerExpired];
} else {
timeCount--;
if(timeCount == 0) {
// display correct dialog with button
[timer invalidate];
[self timerExpired];
}
}
timeRemain.text = [NSString stringWithFormat:@"%d:%02d",timeCount/60, timeCount % 60];
}
- (void) timerExpired {
// display an alert or something when the timer expires.
}
找到了消除抖动的线程解决方案。在 viewDidLoad 方法或 applicationDidFinishLaunching 中,您需要一行,例如:
[NSThread detachNewThreadSelector:@selector(createTimer) toTarget:self withObject:nil];
这将使用 createTimer 方法启动一个线程。但是,您还需要更新 createTimer 方法:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
// start timer
gameTimer = [[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES] retain];
[[NSRunLoop currentRunLoop] addTimer:gameTimer forMode:NSDefaultRunLoopMode];
[runLoop run];
[pool release];
其中大部分是标准线程入口例程的内容。池用于线程所采用的托管内存策略。如果您使用垃圾收集,则不需要这样做,但这并没有什么坏处。 runloop 是一个事件循环,每秒持续执行一次,以在时间流逝时生成事件。主线程中有一个自动创建的运行循环,这是一个特定于这个新线程的运行循环。然后注意最后有一条新语句:
[runLoop run];
这确保了线程将无限期地执行。您可以管理计时器,例如重新启动计时器或在其他方法中将其设置为不同的值。我在代码中的其他位置初始化了计时器,这就是该行已被删除的原因。