深入NSTimer(iOS)

You use the NSTimer class to create timer objects or, more simply, timers. A timer waits until a certain time interval has elapsed and then fires, sending a specified message to a target object. For example, you could create an NSTimer object that sends a message to a window, telling it to update itself after a certain time interval.
这段话的意思简单的来说就是NSTimer是一个定时器,能够在每个确定时间间隔里发送信息给对象。
这篇文章主要解决两个问题:

  • NSTimer和RunLoop
  • NSTimer的销毁事件


/**
     *  定义一个定时器
     *
     */
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(repeat:) userInfo:@{@"key":@"value"} repeats:true];
这是定义一个定时器最简单的方法,也许你也就是这么用的,然而这样的使用方法是后患无穷的,比如说你可以尝试这个时候在界面上放上一个scrollView,比如说tableView,然后滚动这个scrollView,你会发现在滚动scrollView的时候NSTimer停止了工作。但是你如果把上面那段代码改成下面这段:

dispatch_async(dispatch_get_global_queue(0, 0), ^{
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(repeat:) userInfo:@{@"key":@"value"} repeats:true];
        [[NSRunLoop currentRunLoop] run];

    });

这个时候你再来滚动scrollView,比如说我们定义了一个tableView,这个时候你就会发现和使用最开始那段代码不同的是:我们的NSTimer并没有停止工作。

这是为什么?
这里我们引出这篇文章的第一个知识点:RunLoop


在cocoaTouch框架中RunLoop用来循环处理输响应事件(也许描述不是太准确,但是大概就是这个个东西),每个线程都有一个RunLoop,苹果不允许自己创建RunLoop,但是提供了两个方法来获取线程的RunLoop:CFRunLoopGetMain() 和 CFRunLoopGetCurrent()。
我们大概已经猜到了NSTimer是被添加到了RunLoop中来循环处理,事实也的确如此,我们上面用到的NSTimer创建方法:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
这个方法创建好NSTimer以后会自动将它添加到当前线程的RunLoop,所以我们并没有在哪里看到是在什么地方将它添加到RunLoop的,也许我们用下面这个方法你会更加明白:

        /**
         *  创建一个timer , 并将它添加到当前线程的RunLoop
         *
         */
        timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(repeat:) userInfo:@{@"key":@"value"} repeats:true];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

上面这段代码和第一段代码的效果是一模一样的,创建一个NSTimer并把他添加到当前线程的RunLoop。
也许某些细心的同学已经发现了上面的第二段代码出现了这么一行代码:
[[NSRunLoop currentRunLoop] run];
这行代码的作用就是打开当前线程的runLoop,在cocoaTouch框架中只有主线程的RunLoop是默认打开的,而其他线程的RunLoop如果需要使用就必须手动打开,所以如果我们是想要添加到主线程的RunLoop的话,是不需要手动打开RunLoop的。
好像到目前为止我们还是没有解释为什么在滚动scrollView的时候NSTimer会停止工作,这里就涉及到了RunLoop的几个Mode了,他们分别是:

  • Default mode(NSDefaultRunLoopMode)
    默认模式中几乎包含了所有输入源(NSConnection除外),一般情况下应使用此模式。
  • Connection mode(NSConnectionReplyMode)
    处理NSConnection对象相关事件,系统内部使用,用户基本不会使用。
  • Modal mode(NSModalPanelRunLoopMode)
    处理modal panels事件。
  • Event tracking mode(UITrackingRunLoopMode)
    在拖动loop或其他user interface tracking loops时处于此种模式下,在此模式下会限制输入事件的处理。例如,当手指按住UITableView拖动时就会处于此模式。
  • Common mode(NSRunLoopCommonModes)
    这是一个伪模式,其为一组run loop mode的集合,将输入源加入此模式意味着在Common Modes中包含的所有模式下都可以处理。在Cocoa应用程序中,默认情况下Common Modes包含default modes,modal modes,event Tracking modes.可使用CFRunLoopAddCommonMode方法想Common Modes中添加自定义modes。

我们上面的代码,包括第一段代码都是创建NSTimer以后并添加到Runloop的默认模式—— NSDefaultRunLoopMode,而当我们滚动scrollView的时候runloop将会切换到UITrackingRunLoopMode,同事关闭默认模式,而我们的NSTimer很不幸的处于默认模式中,所以当然就停止工作了,而我们的第二段代码同样处于默认模式中,但是由于并不是与主线程处于同一个线程中,所以能够继续工作。
除了像第二段代码那样处理,我们还可以这样来处理NSTimer,能够让他在任何情况下工作:

timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(repeat:) userInfo:@{@"key":@"value"} repeats:true];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

我们将NSTimer放到RunLoop的NSRunLoopCommonModes模式中,如上面所说,这个模式是所有模式的合集,所以在任何环境下都能够工作。
非常好玩的是如果我们将NSTimer放在UITrackingRunLoopMode模式下,那么这个NSTimer平时不工作,但是一旦scrollView开始滚动了,这个NSTimer就开始工作了,也许这样的做法在很特殊的情况下能够有特殊作用,不过好像我目前还没遇到过。
其实终结上面的内容非常简单:

  • NSTimer是什么
  • NSTimer需要添加到RunLoop
  • RunLoop有不同的模式在不同的环境下工作

如果我们不注意NSTimer而直接退出这个页面的话,我们会发现这个页面会发生内存泄漏,而这也就是这篇文章的第二个知识点——NSTimer的销毁。
我们看到在NSTimer的创建过程中我们引用了target:self;所以NSTimer想要销毁必须self先行释放,而self的释放又必须timer进行销毁,这里就发生了循环引用,从而造成了内存泄漏。(这不是弱引用能够解决的)
在Apple的文档中告诉我们:
- (void)invalidate;
是销毁NSTimer的唯一方法,所以我们如果在退出这个页面之前先行调用 [timer invalidate];那么这个页面就不会发生内存泄漏了。我不知道有多少人会这么做:

-(void)dealloc{
    [timer invalidate];
}
不调用 [timer invalidate];永远不会进入 dealloc方法,而不进入 dealloc方法则永远不会调用 [timer invalidate];,这里就又发生冲突了,当然如果我们重载Controller的backBarButton的返回动作然后先进行timer销毁,然后再popController是可以解决这个问题的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值