iOS 倒计时 NSTimer

导语: 新项目有差不多6个倒计时功能,以前都是在根tabbar的controller使用,所以一直也没注意这个问题。最近写的比较多,总结一下。

一、 NSTimer 的使用方法

@interface TimerViewController ()

@property (nonatomic, strong) NSTimer * timer;

@end

@implementation TimerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction{
    NSLog(@"timer run ---");
}
@end

总结来说, 就是三个步骤:

1、创建Timer
2、加入runloop
3、执行响应事件

系统提供了8个创建方法,6个类创建方法,2个实例化方法。

有三个方法直接将timer添加到了当前runloop default mode,而不需要我们自己操作,当然这个runloop只是当前的runloop,模式是default mode:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;

下面五种创建,不会自动添加到runloop,还需调用addTimer: forMode 添加到runloop。

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep;

- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;

二、 NSTimer 和 VC 造成的循环引用

我们修改下上文中我们创建的TimerViewController文件:

@interface TimerViewController ()

@property (nonatomic, strong) NSTimer * timer;

@property (nonatomic, assign) NSInteger  increaseIndex;

@end

@implementation TimerViewController


- (void)viewDidLoad {
    [super viewDidLoad];    
    self.increaseIndex = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction{
    NSLog(@" ---increaseValue: %ld----", (long)self.increaseIndex ++);
}

- (void)dealloc{
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"************ dealloc ***************");
}
@end

进入此页面后, 倒计时触发,timerAction方法开始执行。 点击返回按钮后, 不会触发 dealloc 方法, 内存无法释放。可以看见我们创建一个自增index, 第一次进入页面即可触发, 返回上个页面不会释放, 依然在打印值。再次进入页面触发了另一个timer方法, 同时打印两个index值。清晰的表明了, timer和 VC 循环引用导致了无法释放的问题。

即我们可以认为VC 持有 timer, 而timer的创建方法中参数target使得timer持有VC。

三、 NSTimer 手动销毁解决循环引用

我们继续改造上面的代码:

#import "TimerViewController.h"

@interface TimerViewController ()

@property (nonatomic, strong) NSTimer * timer;

@property (nonatomic, assign) NSInteger  increaseIndex;

@end

@implementation TimerViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton * tempBtn = [[UIButton alloc]  initWithFrame:CGRectMake(100, 100, 100, 30)];
    [tempBtn setBackgroundColor:[UIColor orangeColor]];
    [self.view  addSubview:tempBtn];
    [tempBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.increaseIndex = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction{
    NSLog(@" ---increaseValue: %ld----", (long)self.increaseIndex ++);
}

- (void)btnClick{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)dealloc{
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"************ dealloc ***************");
}
@end

我们在页面返回之前提前点击创建的按钮,执行完 [self.timer invalidate]; self.timer = nil;方法后再进行pop操作。此次发现系统执行了dealloc方法,内存得以释放。 当然,这里只是做个例子来操作,真实情况可以放在类似于 viewWillDisappear:方法中进行销毁。

四、 NSTimer 使用弱引用解决Runloop和timer循环引用

既然是强引用造成的循环引用,那么我们将self弱引用不就可以了,理论上当然是可以了。 我们继续改造代码:

#import "TimerViewController.h"

@interface TimerViewController ()

@property (nonatomic, strong) NSTimer * timer;

@property (nonatomic, assign) NSInteger  increaseIndex;

@end

@implementation TimerViewController


- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.increaseIndex = 0;
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction{
    NSLog(@" ---increaseValue: %ld----", (long)self.increaseIndex ++);
}

- (void)dealloc{
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"************ dealloc ***************");
}
@end

当我们 pop 出该页面以后,并没有调用dealloc方法,内存并没有得到释放,那么到底是什么原因呢?

在 本文的 NSTimer 的使用方法 段落中我们已经介绍了NSTimer的创建方案,无论如何创建。都会将NSTimer 加入到当前的RunLoop当中。所以RunLoop就持有该timer。即VC和timer相互引用,Runloop同时也引用timer。这也是我们在本文中 NSTimer 手动销毁解决循环引用 段落中除了[self.timer invalidate], 还要将 self.timer = nil的原因。

那么我们该如何解决这个问题呢?最简单的方案就是使用 YYKit 中的YYWeakProxy来处理。
继续修改代码:

#import "TimerViewController.h"
#import "YYWeakProxy.h"

@interface TimerViewController ()

@property (nonatomic, strong) NSTimer * timer;

@property (nonatomic, assign) NSInteger  increaseIndex;

@end

@implementation TimerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.increaseIndex = 0;
    YYWeakProxy * weakProxy = [YYWeakProxy proxyWithTarget:self];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakProxy selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction{
    NSLog(@" ---increaseValue: %ld----", (long)self.increaseIndex ++);
}

- (void)dealloc{
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"************ dealloc ***************");
}

@end

此时我们pop后发现系统调用了dealloc方法,内存得以释放。

这里简单解释下YYWeakProxy的原理,YYWeakProxy源码:

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN


@interface YYWeakProxy : NSProxy

@property (nullable, nonatomic, weak, readonly) id target;

- (instancetype)initWithTarget:(id)target;

+ (instancetype)proxyWithTarget:(id)target;

@end

NS_ASSUME_NONNULL_END

#import "YYWeakProxy.h"


@implementation 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;
}

- (NSString *)description {
   return [_target description];
}

- (NSString *)debugDescription {
   return [_target debugDescription];
}

@end

YYWeakProxy的代码非常简单,如果对NSProxy有一定认知的话
,就会发现是重载了父类的方法,将输入的target保存为实例变量,然后返回self。即YYWeakProxy对象会弱引用target对象,通过消息转发处理target事件,这样对应到NSTimer的使用上,就构成了这样的形式:


这样就避免了内存无法释放的问题,很好的解决了NSTimer的循环引用问题。

参考文档

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,612评论 5 471
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,345评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,625评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,022评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,974评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,227评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,688评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,358评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,490评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,402评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,446评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,126评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,721评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,802评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,013评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,504评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,080评论 2 341