Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Start And Stop NSTimer?

The NSTimer class is a bit awkward to use; rather than separating the creation/destruction from the start/stop, it's all rolled together. In other words the timer starts as soon as it's created and stops as soon as it's destroyed.

You therefore need to use the existence of the NSTimer object as a flag to indicate if it's running; something like this:

// Private Methods
@interface MyClass ()
{
    NSTimer *_timer;
}
- (void)_timerFired:(NSTimer *)timer;
@end

@implementation MyClass

- (IBAction)startTimer:(id)sender {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                  target:self
                                                selector:@selector(_timerFired:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}

- (IBAction)stopTimer:(id)sender {
    if ([_timer isValid]) {
        [_timer invalidate];
    }
    _timer = nil;
}

- (void)_timerFired:(NSTimer *)timer {
    NSLog(@"ping");
}

You could always use fire to start a NStimer again

  [timer fire];

To stop it:

  [timer invalidate];
  //remember to set timer to nil after calling invalidate;
  timer = nil;

You can start the timer through

#define kRefreshTimeInSeconds 1
 NSTimer *myTimerName;
 .
 .
 myTimerName = [NSTimer scheduledTimerWithTimeInterval: kRefreshTimeInSeconds 
                                   target:self 
                                   selector:@selector(handleTimer:) 
                                   userInfo:nil
                                   repeats:YES];

Then the delegate function:

-(void)handleTimer: (id) sender 
{       
   //Update Values in Label here
}

And to stop Timer

-(void)stopTimer: (id) sender 
{       
   if(myTimerName)
   {
       [myTimerName invalidate];
        myTimerName = nil;
   }
}