1

我正在使用这段代码:

timer = [NSTimer scheduledTimerWithTimeInterval:2
                                         target:self
                                       selector:@selector(update)
                                       userInfo:nil
                                        repeats:YES];
...

-(void)update {
    NSDate *date = [NSDate date];
    NSString *Currentdate = [date descriptionWithCalendarFormat:@"%b %d, %Y %I:%M:%S %p" 
                                                       timeZone:nil
                                                         locale:nil];
    lbl.text = Currentdate;
}

它工作正常,但我想在运行时将计时器间隔从 2 秒更改为 1 秒。我怎样才能做到这一点?

提前致谢。

4

2 回答 2

10

创建后,您无法更改计时器间隔。

// You have to invalidate it...be careful, 
// this releases it and will crash if done to an already invalidated timer

if (self.timer != nil) {
    [self.timer invalidate];
    self.timer = nil;


//... then declare a new one with the different interval.

timer = [NSTimer scheduledTimerWithTimeInterval:newInterval
                                     target:self
                                   selector:@selector(update)
                                   userInfo:nil
                                    repeats:YES];
}
于 2009-08-20T11:17:47.383 回答
2

只是invalidate旧计时器并创建新计时器。我认为不NSTimer支持更改时间间隔,这在接口和实现中都是多余的。

于 2009-08-20T11:12:47.937 回答