Skip to content

Instantly share code, notes, and snippets.

@doyle
Created June 21, 2009 18:35
Show Gist options
  • Save doyle/133601 to your computer and use it in GitHub Desktop.
Save doyle/133601 to your computer and use it in GitHub Desktop.
// This sample creates a repeating timer and updates a label on the view each time the timer executes
@interface TimerTextViewController : UIViewController {
IBOutlet UILabel *label;
NSTimer *repeatingTimer;
NSUInteger timerCount;
}
@property (nonatomic, retain) NSTimer *repeatingTimer;
-(IBAction)startTimer:(id)sender;
-(IBAction)stopTimer:(id)sender;
-(void)targetMethod:(NSTimer*)theTimer;
@end
@implementation TimerTextViewController
@synthesize repeatingTimer;
-(IBAction)startTimer:(id)sender{
timerCount = 1;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 //interval in seconds
target:self //this is the object that owns the method to execute
selector:@selector(targetMethod:) //this is the method that gets called when the timer ticks, it can be named anything but its signature is important (see below)
userInfo:nil
repeats:YES];
self.repeatingTimer = timer;
}
// the invalidate method stops the timer
-(IBAction)stopTimer:(id)sender{
[repeatingTimer invalidate];
}
//this method could be called anything, but it needs this signature
- (void)targetMethod:(NSTimer*)theTimer {
NSString *countString = [NSString stringWithFormat:@"%lu", timerCount];
[label setText:countString];
timerCount++;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment