7.14. 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=[NSTimerscheduledTimerWithTimeInterval:1.0target:selfselector:@selector(paint:)userInfo:nilrepeats:YES];}-(void)stopPainting{if(self.paintingTimer!=nil){[self.paintingTimerinvalidate];}}-(void)applicationWillResignActive:(UIApplication*)application{[selfstopPainting];}-(void)applicationDidBecomeActive:(UIApplication*)application{[selfstartPainting];}
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 implementation file (.m
file):
#import "AppDelegate.h"@interfaceAppDelegate()@property(nonatomic,strong)NSTimer*paintingTimer;@end@implementationAppDelegate
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:, the time becomes a scheduled timer and will fire the event you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access