O'Reilly logo

iOS 6 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.15. Creating Timers

Problem

You would like to perform a specific task repeatedly with a certain delay. For instance, you want to update a view on your screen every second that your application is running.

Solution

Use a timer:

- (void) paint:(NSTimer *)paramTimer{
  /* Do something here */
  NSLog(@"Painting");
}

- (void) startPainting{
  
  self.paintingTimer = [NSTimer 
                        scheduledTimerWithTimeInterval:1.0
                        target:self
                        selector:@selector(paint:) 
                        userInfo:nil
                        repeats:YES];
  
}

- (void) stopPainting{
  if (self.paintingTimer != nil){
    [self.paintingTimer invalidate];    
  }
}

- (void)applicationWillResignActive:(UIApplication *)application{
  [self stopPainting];
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
  [self startPainting];
}

The invalidate method will also release the timer, so that we don’t have to do that manually. As you can see, we have defined a property called paintingTimer that is declared in this way in the header file (.h file):

#import <UIKit/UIKit.h>

@interface Creating_TimersAppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) NSTimer *paintingTimer;

@end

Discussion

A timer is an object that fires an event at specified intervals. A timer must be scheduled in a run loop. Defining an NSTimer object creates a nonscheduled timer that does nothing but is available to the program when you want to schedule it. Once you issue a call, e.g. scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required