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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值