Timer

Modified

 

Overview

NSTimer class provides a software timer useful for periodic execution of a method.

The example illustrates execution approximately every 1000ms. of a method to display the number of times the method has been called.

The NSTimer object makes callbacks to the method on the main thread so that the UI can be updated but is also sensitive to the time in execution of the method.

Video

Timer
#import "TimerViewController.h"

@implementation TimerViewController

NSTimer *timer;
long ticks;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

-(IBAction) start: (id) sender{
    ticks = 0;
   timer = [NSTimer  scheduledTimerWithTimeInterval: 1.0 
                                target: self 
                                selector: @selector(timerCallback:) 
		           userInfo: nil 
			repeats: YES];		 
}

-(IBAction) stop: (id) sender{
    	if(timer) {
		[timer invalidate];		// Stop timer callbacks
		timer = nil;
	}
}

- (void) timerCallback:(NSTimer *) theTimer {
    ticks++;
    [timeLabel setText:[NSString stringWithFormat:@"%d", ticks]];
}

@end