iOS内存管理04 -- 定时器

定时器

  • 在iOS开发中定时器有三种分别为NSTimerCADisplayLinkGCD定时器,GCD定时器在 iOS底层系列24 -- 多线程的实现 这篇文章已经提到过是通过dispatch_source_t实现的;

定时器的精度问题

  • dispatch_source_t相对于NSTimer,CADisplayLink更加精准,因为dispatch_source_t是基于系统内核实现的,不依赖于RunLoop机制;
  • NSTimer与CADisplayLink都是基于RunLoop(运行循环)实现的,也就是说NSTimer与CADisplayLink必须加入到RunLoop中才能正常的工作,由于RunLoop的运行机制,会导致出现不可避免的误差,产生误差的原因如下:
  • RunLoop每跑完一次圈再去检查当前累计时间是否已经达到定时器所设置的间隔时间,如果未达到,RunLoop将进入下一轮任务循环,待任务结束之后再去检查当前累计时间,如果RunLoop在处理耗时任务时,可能会导致累计时间已经超过了定时器的间隔时间,故定时器的回调会存在一定的误差;
  • 在开发中如果对定时器精度有过高的要求,建议使用GCD定时器;

定时器引发的内存泄漏问题

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,strong)CADisplayLink *link;
@property(nonatomic,strong)NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1秒钟会调用60次linkTest方法
    self.link = [CADisplayLink displayLinkWithTarget:self selector:@selector(linkTest)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeTest) userInfo:nil repeats:YES];
}

- (void)dealloc{
    NSLog(@"%s",__func__);
    [self.link invalidate];
    [self.timer invalidate];
}

- (void)linkTest{
    NSLog(@"%s",__func__);
}

- (void)timeTest{
    NSLog(@"%s",__func__);
}
@end
  • 定义初始化了两种定时器,NSTimer和CADisplayLink,在运行过程中只选择其中一种定时器运行测试,发现当控制器弹栈时,控制器没有调用dealloc方法且定时器依然在执行回调,说明控制器与定时器都存在内存泄漏;
  • 原因如下图所示:
Snip20210404_2.png
  • 定时器加入RunLoop中,RunLoop强引用定时器(RunLoop始终都存在,除非app退出),定时器又强引用视图控制器,导致控制器在弹栈的时候dealloc无法执行,定时器无法被销毁;
第一种解决方案:
  • NSTimer初始化时使用block创建任务回调,则NSTimer不会对控制器产生强引用,那么控制器在弹栈时dealloc方法正常执行,然后执行定时器的invalidate,定时器销毁,代码如下所示:
- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf timeTest];
    }];
}

- (void)dealloc{
    NSLog(@"%s",__func__);
    [self.timer invalidate];
}

- (void)timeTest{
    NSLog(@"%s",__func__);
}
  • 很可惜CADisplayLink的创建只能使用target的方式,系统没有提供block的方式,如何解决这个问题?答案是引入第三方target对象,即让CADisplayLink强引用第三方target对象,然后第三方target对象弱引用控制器,结构如下图所示:
Snip20210404_4.png
  • 代码实现如下:
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1秒钟会调用60次linkTest方法
    self.link = [CADisplayLink displayLinkWithTarget:[YYTimerObject timerObjectWithTarget:self] selector:@selector(linkTest)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
}

- (void)dealloc{
    NSLog(@"%s",__func__);
    [self.link invalidate];
}

- (void)linkTest{
    NSLog(@"%s",__func__);
}
  • 第三方target类YYTimerObject
#import <Foundation/Foundation.h>

@interface YYTimerObject : NSObject

@property(nonatomic,weak)id target;

+ (instancetype)timerObjectWithTarget:(id)target;

@end
#import "YYTimerObject.h"

@implementation YYTimerObject

+ (instancetype)timerObjectWithTarget:(id)target{
    YYTimerObject *object = [[YYTimerObject alloc]init];
    object.target = target;
    return object;
}

//消息的快速转发 转发给控制器执行定时器的回调方法
- (id)forwardingTargetForSelector:(SEL)aSelector{
    return self.target;
}
@end
  • YYTimerObject有一个弱引用指针,引用外界的target对象即视图控制器;
  • YYTimerObject是没有linkTest方法的,所以我们想要让控制器去执行定时器的回调linkTest方法,这里用到了消息的快速转发技术,将消息转发给控制器去处理,至于消息的快速转发技术在 iOS底层系列14 -- 消息流程的动态方法决议与转发 有详细介绍;
  • 同理NSTimer使用target初始化,也可以借助第三方YYTimerObject作为target进行处理,解决内存泄漏问题,代码如下:
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[YYTimerObject timerObjectWithTarget:self] selector:@selector(timeTest) userInfo:nil repeats:YES];
}

- (void)dealloc{
    NSLog(@"%s",__func__);
    [self.timer invalidate];
}

- (void)timeTest{
    NSLog(@"%s",__func__);
}

NSProxy

  • NSProxy是与NSObject同一级别的类,专门用来做消息转发的,下面我们使用NSProxy对上面的第三方target对象进行改造,新建一个继承自NSProxy的类YYProxy,代码如下:
#import <Foundation/Foundation.h>

@interface YYProxy : NSProxy

@property(nonatomic,weak)id target;

+ (instancetype)proxyWithTarget:(id)target;

@end
#import "YYProxy.h"

@implementation YYProxy

+ (instancetype)proxyWithTarget:(id)target{
    YYProxy *proxy = [YYProxy alloc];
    proxy.target = target;
    return proxy;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
    return [self.target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation{
    [invocation invokeWithTarget:self.target];
}
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[YYProxy proxyWithTarget:self] selector:@selector(timeTest) userInfo:nil repeats:YES];
}

- (void)dealloc{
    NSLog(@"%s",__func__);
    [self.timer invalidate];
}

- (void)linkTest{
    NSLog(@"%s",__func__);
}

- (void)timeTest{
    NSLog(@"%s",__func__);
}
@end
  • 看到使用YYProxy也能解决定时器的循环引用,使用NSProxy的效率会更高,原因在于我们使用NSObject作为第三方target对象,在寻找目标方法时会经历方法的缓存查找,继承链上查找,动态方法决议,最后才进入消息的转发流程,但是如果使用NSProxy在寻找目标方法时,只会在本类中查找,如果没有直接进入消息转发流程,所以效率会更高;

GCD定时器

  • 先上代码如下:
#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong)dispatch_source_t gcd_timer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    //创建GCD定时器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置启动时间与时间间隔
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), 1 * NSEC_PER_SEC, 0);

    //设置GCD定时器回调
    dispatch_source_set_event_handler(timer, ^{
        NSLog(@" ---- ");
    });
    //启动定时器
    dispatch_resume(timer);
    self.gcd_timer = timer;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容