Saturday, April 27, 2013

NSTimer setFireDate example ios

setFireDate:
Resets the firing time of the receiver to the specified date.
- (void)setFireDate:(NSDate *)date
Parameters
date
The new date at which to fire the receiver. If the new date is in the past, this method sets the fire time to the current time.
Discussion of [NSTimer setFireDate]
You typically use this method to adjust the firing time of a repeating timer. Although resetting a timer’s next firing time is a relatively expensive operation, it may be more efficient in some situations. For example, you could use it in situations where you want to repeat an action multiple times in the future, but at irregular time intervals. Adjusting the firing time of a single timer would likely incur less expense than creating multiple timer objects, scheduling each one on a run loop, and then destroying them.[NSTimer setFireDate]
You should not call this method on a timer that has been invalidated, which includes non-repeating timers that have already fired. You could potentially call this method on a non-repeating timer that had not yet fired, although you should always do so from the thread to which the timer is attached to avoid potential race conditions.
Example of [NSTimer setFireDate]

-(IBAction)clicked:(id)sender
{
    if ([startStop.titleLabel.text isEqualToString:@"Start"]) 
    {
        [startStop setTitle:@"Pause" forState:UIControlStateNormal];
        [startStop setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countUp) userInfo:nil repeats:YES];
        timerDown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];

    } else if ([startStop.titleLabel.text isEqualToString:@"Pause"])
    {
        [startStop setTitle:@"Resume" forState:UIControlStateNormal];
        [startStop setTitleColor:[UIColor colorWithRed:0/255 green:0/255 blue:255/255 alpha:1.0] forState:UIControlStateNormal];

        pauseStart = [[NSDate dateWithTimeIntervalSinceNow:0] retain];
        previousFireDate = [[timer fireDate] retain];
        [timer setFireDate:[NSDate distantFuture]];

    } else if ([startStop.titleLabel.text isEqualToString:@"Resume"])
    {
        [startStop setTitle:@"Pause" forState:UIControlStateNormal];
        [startStop setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

        float pauseTime = -1*[pauseStart timeIntervalSinceNow];
        [timer setFireDate:[NSDate dateWithTimeInterval:pauseTime sinceDate:previousFireDate]];
        [pauseStart release];
        [previousFireDate release];
    }
}