iOS Runloop面试题(解释一下 NSTimer。)以及NSTimer不准的问题及解决以及CADisplayLink、NSTimer使用注意(解决CADisplayLink、NSTimer循环引

解释一下 NSTimer

NSTimer 其实就是 CFRunLoopTimerRef,他们之间是 toll-free bridged 的。一个 NSTimer 注册到 RunLoop后,RunLoop 会为其重复的时间点注册好事件。例如 10:0010:1010:20 这几个时间点。RunLoop 为了节省资源,并不会在非常准确的时间点回调这个TimerTimer 有个属性叫做 Tolerance (宽容度),标示了当时间点到后,容许有多少最大误差。

如果某个时间点被错过了,例如执行了一个很长的任务,则那个时间点的回调也会跳过去,不会延后执行。就比如等公交,如果 10:10 时我忙着玩手机错过了那个点的公交,那我只能等 10:20 这一趟了。

CADisplayLink 是一个和屏幕刷新率一致的定时器(但实际实现原理更复杂,和 NSTimer 并不一样,其内部实际是操作了一个 Source)。如果在两次屏幕刷新之间执行了一个长任务,那其中就会有一帧被跳过去(和 NSTimer相似),造成界面卡顿的感觉。在快速滑动 TableView 时,即使一帧的卡顿也会让用户有所察觉。Facebook 开源的 AsyncDisplayLink 就是为了解决界面卡顿的问题,其内部也用到了 RunLoop


NSTimer不准的问题及解决

原因

1、NSTimer被添加在mainRunLoop中,模式是NSDefaultRunLoopMode,mainRunLoop负责所有主线程事件,例如UI界面的操作,复杂的运算,这样就会造成timer的阻塞、

2、模式的切换,当创建的timer被加入到NSDefaultRunLoopMode时,此时如果有滑动UIScrollView的操作,runLoop 的mode会切换为TrackingRunLoopMode,这是timer会停止回调。

解决

方法一

1、在子线程中创建timer,在主线程进行定时任务的操作

2、在子线程中创建timer,在子线程中进行定时任务的操作,需要UI操作时切换回主线程进行操作

方法二

使用GCD定时器

/**
 参数1:代表创建一个定时器
 参数4:队列
 这里的强引用是因为,当我定时器延时几秒调用的时候,局部变量就销毁了,我们需要强引用起来
 */
 
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
 
/**
 设置定时器
 参数1:定时器对象
 参数2:GCD dispatch_time_t 里面的都是纳秒 创建一个距离现在多少秒开启的任务
 参数3:间隔多少秒调用一次
 */
dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, 1.0), 1.0 * NSEC_PER_SEC, 0); // 设置回调
 
dispatch_source_set_event_handler(self.timer, ^{
    NSLog(@"doSomething");
});
 
// 启动
dispatch_resume(self.timer);
--------------------------------------------------------------------------------------------------------------------------------

iOS 常见面试题--CADisplayLink、NSTimer使用注意(解决CADisplayLink、NSTimer循环引用问题)

一、问题

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定时器
封装好的定时器 可以放到任何项目中使用

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值