NSTimer问题

时间:2009-08-20 11:02:20

标签: iphone nstimer

我正在使用此代码:

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秒。我怎么能这样做?

提前致谢。

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:2)

只需invalidate旧计时器并创建新计时器。我不认为NSTimer支持更改时间间隔,这在界面和实现中都是一个额外的障碍。