tags:

views:

546

answers:

3

I am using this code:

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;
}

It works fine but I want to change timer interval from 2 seconds to 1 second at run time. How can I do this?

Thanks in advance.

+1  A: 

Just invalidate the old timer and create new. I don’t think NSTimer supports changing the time interval, it would be an extra cruft both in the interface and the implementation.

zoul
+4  A: 

You can't change a timer interval after it's been created.

// 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];
}
willc2
A: 

Thanks for the replay