美文网首页
NSTimer CADisplayLink GCD计时器的深入探

NSTimer CADisplayLink GCD计时器的深入探

作者: xuwen_chen | 来源:发表于2019-03-23 15:28 被阅读0次

    关于NSTimer CADisplayLink GCD计时器的杂谈

    ** NSTimer **

    iOS中最常用的定时器 一般来说计时是相对准确 但是如果在当前循环中有耗时操作 下一次定时可能就会延后 (在一个循环中加入一个for循环并进行打印操作可以明显检测到)另外把计时器加入的RunLoop的模式也会对他有影响 使用下面的代码时候 当用户进行UI交互操作的时候(比如滑动tableView)主线程切换到TrackingRunLoopModel 在这种模式下定时器不会触发

     [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopDefaultModel];
    

    另外NSTimer容易造成循环引用 在下述常规使用中 就容易造成循环引用 如果没及时调用 invalidate 方法容易造成内存泄漏 一般都是控制器没被销毁的大内存泄漏 比如一般错误的写法在dealloc 里面调用

    [_timer invalidate ]; 
    _timer = nil; 
    

    因为NSTimer 会强引用target NSRunLoop又会持有NSTimer 使用者(target) 同时又持有NSTimer 这就造成了循环引用

    第一种误区 我们可能会将NSTimer声明为弱引用 但是target的释放依赖NSTimer的释放 而NSTimer的释放在target的dealloc中 所以还是会循环引用
    第二种误区 将NSTimer 弱引用self 但是NSTimer 还是会强引用target 估计NSTimer内部声明了一个__strong指针

     self.timer1 = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(timerMethod1) userInfo:nil repeats:NO];
    

    解决循环引用的办法
    第一种 使用 分类 使用的时候只需要block里面避免强引用造成的循环引用即可 有点类似iOS10.0以后系统提供的block的接口

    + (NSTimer *)AZ_scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats
    {
        void (^block)() = [inBlock copy];
        NSTimer * timer = [self scheduledTimerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats];
        return timer;
    }
    
    + (NSTimer *)AZ_timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats
    {
        void (^block)() = [inBlock copy];
        NSTimer * timer = [self timerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats];
        return timer;
    }
    
    + (void)__executeTimerBlock:(NSTimer *)inTimer;
    {
        if([inTimer userInfo])
        {
            void (^block)() = (void (^)())[inTimer userInfo];
            block();
        }
    }
    

    另外 在创建NSTimer的时候先要将定时器停止 ,不然可能会出现僵尸定时器 ,导致不可预估的错误

    第二种 GCD自己实现Timer YYKit里面有现成的类YYTimer

    第三种 代理Proxy NSProxy 相当于一个中间代理人 并将消息转发给真正实现这个方法的类
    使用的时候只需要将self 替换成 [YYWeakProxy proxyWithTarget:self] 借用了YYWeakProxy里面的实现

    - (instancetype)initWithTarget:(id)target {
       _target = target;
       return self;
    }
    
    + (instancetype)proxyWithTarget:(id)target {
       return [[YYWeakProxy alloc] initWithTarget:target];
    }
    
    - (id)forwardingTargetForSelector:(SEL)selector {
       return _target;
    }
    
    - (void)forwardInvocation:(NSInvocation *)invocation {
       void *null = NULL;
       [invocation setReturnValue:&null];
    }
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
       return [NSObject instanceMethodSignatureForSelector:@selector(init)];
    }
    
    - (BOOL)respondsToSelector:(SEL)aSelector {
       return [_target respondsToSelector:aSelector];
    }
    
    - (BOOL)isEqual:(id)object {
       return [_target isEqual:object];
    }
    
    - (NSUInteger)hash {
       return [_target hash];
    }
    
    - (Class)superclass {
       return [_target superclass];
    }
    
    - (Class)class {
       return [_target class];
    }
    
    - (BOOL)isKindOfClass:(Class)aClass {
       return [_target isKindOfClass:aClass];
    }
    
    - (BOOL)isMemberOfClass:(Class)aClass {
       return [_target isMemberOfClass:aClass];
    }
    
    - (BOOL)conformsToProtocol:(Protocol *)aProtocol {
       return [_target conformsToProtocol:aProtocol];
    }
    
    - (BOOL)isProxy {
       return YES;
    }
    

    个人比较推荐第三种方式 没有对NSTimer 进行耦合 对原生代码的入侵比较小 同时CADisplayLink 也可以使用上述的三种方式 解除循环引用

    CADisplayLink

    CADisplayLink 是一个让我们以和屏幕刷新率相同的频率的定时器 (利用这一点可以在测试APP时悬浮一个窗口在window上实时查看实时帧率) 当CADispLink以特定的模式注册到runloop之后 当屏幕需要刷新的时候会调用CADisplayLink绑定的target的selector 并且这个时候可以读取到这次调用的时间戳
    CADisplay适合UI不停重绘的场合 比如刚说的实时显示当前屏幕刷新率的label FLAnimatedImageView YYAnimatedImageView 里面的加载gif图 文字闪烁渐入渐出的动画效果的RQShineLabel

    GCDTimer

    GCDTimer不受当前RunLoopMode的影响 但是计时也不是绝对准确的 当GCD内部管理的所有线程都被占用的时候 其触发的事件将被延迟(这种很少见 几乎不可能)

       __block NSInteger remain = showtime*20; //倒计时时间
       __block NSInteger count = 0;
       
       dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
       _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
       dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 0.05 * NSEC_PER_SEC, 0); // 每秒执行
       @weakify(self);
       dispatch_source_set_event_handler(_timer, ^{
           dispatch_async(dispatch_get_main_queue(), ^{
               if (count >= remain) {
                   dispatch_source_cancel(_timer);
                   weak_self.viewLayer.strokeStart = 1;
                   [weak_self dismiss];                         // 关闭界面
               } else {
                   weak_self.viewLayer.strokeStart += 0.01;
                   count++;                               //剩余时间进行自加
               }
           });
       });
       dispatch_resume(_timer);
    

    注意计时器 不一定是在主线程进行 所以UI相关的操作要放到主线程进行 timer对象要被持有 如果没被持有 定会器销毁 timer就不会正常运行

    相关文章

      网友评论

          本文标题:NSTimer CADisplayLink GCD计时器的深入探

          本文链接:https://www.haomeiwen.com/subject/kcesvqtx.html