美文网首页
iOS 常见面试题--CADisplayLink、NSTimer

iOS 常见面试题--CADisplayLink、NSTimer

作者: 奋斗的小马达 | 来源:发表于2021-02-22 15:21 被阅读0次

    一、问题

    1、CADisplayLink、NSTimer会对target产生强引用,如果target又对它们产生强引用,那么就会引发循环引用
    2、CADisplayLink、NSTimer  可能会不准时 (原因是 CADisplayLink、NSTimer  底层都是基于runloop   CADisplayLink、NSTimer 在计时的时候是runloop跑一圈记一次        runloop在跑圈的时候 每次处理的事件可能会不同 因此消耗的时间也会不同  所以时间会出现误差 )
    
    

    案例:有A,B两个控制器 在B控制器中创建一个定时器 且创建时开启定时器 然后在B控制器的 dealloc 方法中取消定时器 只要代码如下

    B控制器
    
    @property (strong, nonatomic) CADisplayLink *link;
    @property (strong, nonatomic) NSTimer *timer;
    
    //类型一
     self.link = [CADisplayLink displayLinkWithTarget:[FCProxy proxyWithTarget:self] selector:@selector(linkTest)];
        [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
        
    //类型二
    //    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[FCProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
    
    
    - (void)timerTest
    {
        NSLog(@"%s", __func__);
    }
    
    - (void)linkTest
    {
        NSLog(@"%s", __func__);
    }
    
    - (void)dealloc
    {
        NSLog(@"%s", __func__);
        [self.link invalidate];
    //    [self.timer invalidate];
    }
    
    
    从B返回A之后 会发现 B控制器并未被销毁 且定时器还在继续执行
    原因分析:B 强引用 定时器 定时器又强引用 B 导致 循环引用
    
    

    二、解决方案(解决循环引用问题)

    1、如果是NSTimer 可以使用block

    
    @property (strong, nonatomic) NSTimer *timer;
    
       __weak typeof(self) weakSelf = self;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
           [weakSelf timerTest];
       }];
    
    分析:self 对 NSTimer 强引用  NSTimer 对self 弱引用  因此能够解决循环引用问题
    
    

    2、使用代理对象(NSProxy)(NSTimer和CADisplayLink都可以使用)

    1、创建一个 继承于NSProxy的类 FCProxy
    
    FCProxy.h
    @interface FCProxy : NSProxy
    + (instancetype)proxyWithTarget:(id)target;
    @property (weak, nonatomic) id target;
    @end
    
    FCProxy.m
    
    #import "FCProxy.h"
    
    @implementation FCProxy
    
    + (instancetype)proxyWithTarget:(id)target
    {
        // NSProxy对象不需要调用init,因为它本来就没有init方法
        FCProxy *proxy = [FCProxy alloc];
        proxy.target = target;
        return proxy;
    }
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
    {
        return [self.target methodSignatureForSelector:sel];
    }
    
    - (void)forwardInvocation:(NSInvocation *)invocation
    {
        [invocation invokeWithTarget:self.target];
    }
    @end
    
    
    2、使用方式
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[FCProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
    }
    
    - (void)timerTest
    {
        NSLog(@"%s", __func__);
    }
    
    - (void)dealloc
    {
        NSLog(@"%s", __func__);
        [self.timer invalidate];
    }
    
    
    分析 :控制器 对 定时器 强引用  定时器对 代理对象强引用  代理对象 对 控制器弱引用
    这样控制器就没有谁对他进行强引用 所以可以释放解决循环引用问题
    

    三、解决方案(解决时间不准和循环引用问题)

    GCD定时器之所以准确 是因为 GCD定时器是基于内核来实现的,所以不会出现误差 同时也不用考虑滑动对定时器的影响
    
    使用GCD定时器 (创建一个CGD定时器类FCTimer  可以供整个项目使用) 
    

    FCTimer.h

    @interface FCTimer : NSObject
    
    
    /// 任务放在block中执行
    /// @param task 任务
    /// @param start 几秒之后执行
    /// @param interval 时间间隔
    /// @param repeats 是否重复
    /// @param async 是否放在主线程执行
    + (NSString *)execTask:(void(^)(void))task
               start:(NSTimeInterval)start
            interval:(NSTimeInterval)interval
             repeats:(BOOL)repeats
               async:(BOOL)async;
    
    
    /// r任务放在函数中执行
    /// @param target 执行对象
    /// @param selector 执行方法
    /// @param start 几秒之后执行
    /// @param interval 时间间隔
    /// @param repeats 是否重复
    /// @param async 是否放在主线程执行
    + (NSString *)execTask:(id)target
                  selector:(SEL)selector
                     start:(NSTimeInterval)start
                  interval:(NSTimeInterval)interval
                   repeats:(BOOL)repeats
                     async:(BOOL)async;
    
    
    /// 取消定时
    /// @param name 定时器的名字
    + (void)cancelTask:(NSString *)name;
    
    

    FCTimer.m

    #import "FCTimer.h"
    
    @implementation FCTimer
    
    static NSMutableDictionary *timers_;
    dispatch_semaphore_t semaphore_;
    + (void)initialize
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            timers_ = [NSMutableDictionary dictionary];
            semaphore_ = dispatch_semaphore_create(1);
        });
    }
    
    + (NSString *)execTask:(void (^)(void))task start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeats:(BOOL)repeats async:(BOOL)async
    {
        if (!task || start < 0 || (interval <= 0 && repeats)) return nil;
        
        // 队列
        dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
        
        // 创建定时器
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        
        // 设置时间
        dispatch_source_set_timer(timer,
                                  dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC),
                                  interval * NSEC_PER_SEC, 0);
        
        
        dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
        // 定时器的唯一标识
        NSString *name = [NSString stringWithFormat:@"%zd", timers_.count];
        // 存放到字典中
        timers_[name] = timer;
        dispatch_semaphore_signal(semaphore_);
        
        // 设置回调
        dispatch_source_set_event_handler(timer, ^{
            task();
            
            if (!repeats) { // 不重复的任务
                [self cancelTask:name];
            }
        });
        
        // 启动定时器
        dispatch_resume(timer);
        
        return name;
    }
    
    + (NSString *)execTask:(id)target selector:(SEL)selector start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeats:(BOOL)repeats async:(BOOL)async
    {
        if (!target || !selector) return nil;
        
        return [self execTask:^{
            if ([target respondsToSelector:selector]) {
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                [target performSelector:selector];
    #pragma clang diagnostic pop
            }
        } start:start interval:interval repeats:repeats async:async];
    }
    
    + (void)cancelTask:(NSString *)name
    {
        if (name.length == 0) return;
        
        dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
        
        dispatch_source_t timer = timers_[name];
        if (timer) {
            dispatch_source_cancel(timer);
            [timers_ removeObjectForKey:name];
        }
    
        dispatch_semaphore_signal(semaphore_);
    }
    
    @end
    

    使用方式

    @property (copy, nonatomic) NSString *task;
    
    
    
        self.task = [FCTimer execTask:self
                             selector:@selector(doTask)
                                start:2.0
                             interval:1.0
                              repeats:YES
                                async:NO];
        
    //    self.task = [FCTimer execTask:^{
    //        NSLog(@"111111 - %@", [NSThread currentThread]);
    //    } start:2.0 interval:-10 repeats:NO async:NO];
    
    

    项目开发过程中 选择使用定时器时 建议选择GCD定时器
    封装好的定时器 可以放到任何项目中使用

    相关文章

      网友评论

          本文标题:iOS 常见面试题--CADisplayLink、NSTimer

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