iOS GCD定時器的使用

  1. #import "ViewController.h"  
  2.   
  3. @interface ViewController ()  
  4. {  
  5.     dispatch_source_t _timer;  
  6.     NSArray *arr;  
  7. }  
  8.   
  9. @end  
  10.   
  11. @implementation ViewController  
  12.   
  13. - (void)viewDidLoad {  
  14.     [super viewDidLoad];  
  15.     // Do any additional setup after loading the view, typically from a nib.  
  16.     self.view.backgroundColor = [UIColor redColor];  
  17.      
  18.     [self startGCDTimer];  
  19. }  
  20. -(void) startGCDTimer{  
  21.     NSTimeInterval period = 1.0//設置時間間隔  
  22.     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
  23.     _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 00, queue);  
  24.     dispatch_source_set_timer(_timer, dispatch_walltime(NULL0), period * NSEC_PER_SEC, 0); //每秒執行  
  25.     dispatch_source_set_event_handler(_timer, ^{  
  26.         //在這裏執行事件  
  27.         NSLog(@"每秒執行test");  
  28.     });  
  29.       
  30.     dispatch_resume(_timer);  
  31. }  
  32.   
  33.   
  34. -(void) pauseTimer{  
  35.     if(_timer){  
  36.         dispatch_suspend(_timer);  
  37.     }  
  38. }  
  39. -(void) resumeTimer{  
  40.     if(_timer){  
  41.         dispatch_resume(_timer);  
  42.     }  
  43. }  
  44. -(void) stopTimer{  
  45.     if(_timer){  
  46.         dispatch_source_cancel(_timer);  
  47.         _timer = nil;  
  48.     }  
  49. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章