定时器的使用

Posted on 2016-07-07 01:08  柠檬片  阅读(116)  评论(0)    收藏  举报

1.第一种定时器

//添加定时器

//TimeInterval 每隔多少秒执行一次事件

//target 又谁调用要执行的事件

//selector 要执行的事件

//userInfo 给要执行的事件传递的参数

//repeats 是否重复执行

  self.timer=  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChage) userInfo:nil repeats:YES];

//设置定时器不工作

[ self.timer invalidate];

 

 1  //1.创建NSTimer
 2     NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(show) userInfo:nil repeats:YES];
 3     
 4     //2.添加到runloop
 5     //把定时器添加到但当前的runloop中,并且选择默认运行模式kCFRunLoopDefaultMode == NSDefaultRunLoopMode
 6     
 7     //当runloop的运行模式为NSDefaultRunLoopMode时候,定时器工作
 8     //    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
 9     
10     //当runloop的运行模式为UITrackingRunLoopMode时候,定时器工作
11     //     [[NSRunLoop currentRunLoop]addTimer:timer forMode:UITrackingRunLoopMode];
12     
13     //    NSRunLoopCommonModes标记,
14     /*
15      0 : <CFString 0x109af3a40 [0x108c687b0]>{contents = "UITrackingRunLoopMode"}
16      2 : <CFString 0x108c88b40 [0x108c687b0]>{contents = "kCFRunLoopDefaultMode"}
17      */
18     [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
创建NSTimer的另一种方式

 

 

 

    

 2.第二种定时器

    //创建CADisplayLink (当每一屏幕刷新就会调用 每一秒刷新60)

    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];

    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

 

3.第三种定时器(GCD定时器)

 1 -(void)gcdTimer
 2 {
 3     //0.创建队列
 4     dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
 5     
 6     NSLog(@"%s",__func__);
 7     //1.创建一个GCD定时器
 8     /*
 9      第一个参数:表明创建的是一个定时器
10      第四个参数:队列
11      */
12     dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
13     
14     self.timer = timer;
15     //2.设置定时器的开始时间,间隔时间,精准度
16     /*
17      第1个参数:要给哪个定时器设置
18       第2个参数:开始时间
19       第3个参数:间隔时间
20       第4个参数:精准度 一般为0 提高程序的性能
21      GCD的单位是纳秒
22      */
23     dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 10 * NSEC_PER_SEC);
24     
25     //3.设置定时器要调用的方法
26     dispatch_source_set_event_handler(timer, ^{
27         NSLog(@"-----");
28     });
29     
30     //4.启动
31     dispatch_resume(timer);
32 }
GCD定时器