Skip to content

Instantly share code, notes, and snippets.

@berikv
Created December 7, 2011 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berikv/1442391 to your computer and use it in GitHub Desktop.
Save berikv/1442391 to your computer and use it in GitHub Desktop.
GCD timer in a UIViewController
@interface MyViewController()
@property (nonatomic, assign) dispatch_source_t timer;
- (void)handleTimer;
@end
@implementation
@synthesize timer=timer_;
- (id)init {
self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil];
if (self) {
// Timer setup code:
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
if (timer) {
__block MyViewController *blockSelf = self;
dispatch_source_set_event_handler(timer, ^{
// This code is called by the timer
[blockSelf handleTimer];
});
self.timer = timer;
}
}
return self;
}
- (void)viewWillAppear {
if (self.timer) {
dispatch_resume(self.timer);
}
}
- (void)viewWillDisapear
- (void)handleTimer {
NSLog(@"Timer triggered");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment