计时器延迟 NSTimer和CADisplaylink GCD中的延迟

1,NStimer时间间隔比较大,大于1秒;

  CADisplayLink 时间间隔比较小,0.01秒;

2,创建启动计时器:

[NSTimer scheduledTimeInterval:0.5 target:self selector:@select(nextImage) userInfo:nil repeat:Yes];

3,停止计时器

调用NSTimer对象的invalidate方法。一旦停止就不能再用了,只能重新创建一个新的计时器;

[self.timer invalidate];

self.timer = nil;//计时器已经废了,指向nil;

4,nstimer 优先级比较低,有同界面的其他空间接收交行的时候,NSTimer会停止,所以我们要设置优先级;

修改优先级与其他控件相同:

1.获取当前消息循环对象:

NSRunloop *runloop = [NSRunLoop currentRunLoop];

改变self.timer对象的优先级

runloop addTimer:self.timer forMode:NSRunLoopCommonModes];

 

GCD中的延迟:dispatch_after snippet - GCD:Dispatch After方法

dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0 * NSEC_PER_SEC)),dispatch_get_main_queue(),^{

  延迟后要实现的方法。

});


关于OC中的几种代码延迟执行方式 第一种:
[UIView animateWithDuration:3 delay:3 options:1 animations:^{
        self.btn.transform = CGAffineTransformMakeTranslation(300, 400);
    } completion:^(BOOL finished) {
        NSLog(@"view animation结束");
    }];//不会阻塞线程,animations  block中的代码对于是支持animation的代码,才会有延时效果,
         对于不支持animation的代码 则 不会有延时效果
第二种:
[NSThread sleepForTimeInterval:3];//阻塞线程,浪费性能 ,一般不推荐用
第三种:最常用
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       
    });//定制了延时执行的任务,不会阻塞线程,效率较高(推荐使用)
  
第四种:
[self performSelector:@selector(test) withObject:nil afterDelay:3];//不阻塞线程

posted @ 2016-05-27 12:25  蜗牛才是大牛  阅读(406)  评论(0编辑  收藏  举报