美文网首页
NSTimer中的NSRunloop

NSTimer中的NSRunloop

作者: 孟文 | 来源:发表于2016-09-12 12:50 被阅读0次

NSTimer与NSRunloop平时的运用

一, 简单的了解NSRunloop

从字面上看:运行循环、跑圈

其实它内部就是do-while循环,在这个循环内部不断的处理各种任务(比如Source、Timer、Observer)

一个线程对应一个RunLoop,主线程的RunLoop默认已经启动,子线程的RunLoop需要手动启动(调用run方法)

RunLoop只能选择一个Mode启动,如果当前Mode中没有任何Soure、Timer、Observer,那么就直接退出RunLoop

二, 需要了解NSRunloop常用的Model:

NSDefaultRunLoopMode; NSRunLoopCommonModes.开发中运用最多的就是这两种,想深入了解的可以多看一些大牛的技术博客,小白技术有限,就不坑谁谁了.

三, 定时器的创建

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

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

使用第一种方法创建的 定时器必须要手动加到NSRunloop中.第二种方法创建的会自动把timer加入MainRunloop的NSDefaultRunLoopMode中,当然也可以修改它的模式.

四, 定时器销毁(适当的时机关掉,很重要)

[timer invalidate];

timer = nil;

五, 运用

当使用NSTimer的scheduledTimerWithTimeInterval方法时。事实上此时Timer会被加入到当前线程的Run Loop中,且模式是默认的NSDefaultRunLoopMode。而如果当前线程就是主线程,也就是UI线程时,某些UI事件,比如UIScrollView的拖动操作,会将Run Loop切换成NSEventTrackingRunLoopMode模式,在这个过程中,默认的NSDefaultRunLoopMode模式中注册的事件是不会被执行的。也就是说,此时使用scheduledTimerWithTimeInterval添加到Run Loop中的Timer就不会执行。

所以为了设置一个不被UI干扰的Timer,我们需要手动创建一个Timer,然后使用NSRunLoop的addTimer:forMode:方法来把Timer按照指定模式加入到Run Loop中。这里使用的模式是:NSRunLoopCommonModes,这个模式等效于NSDefaultRunLoopMode和NSEventTrackingRunLoopMode的结合

注: 定时器会有延时的,很难做到一点不差.

感谢iOS技术牛人无私的分享,让我这个小白一天一天的成长!!!!!!!

相关文章

  • NSTimer

    深入NSTimer(iOS)iOS 中的 NSTimer关于NSRunLoop和NSTimer的深入理解

  • NSTimer中的NSRunloop

    NSTimer与NSRunloop平时的运用 一, 简单的了解NSRunloop 从字面上看:运行循环、跑圈 其实...

  • runloop关系篇

    NSRunloop关系篇 1.NSRunloop 与 NSTimer .https://blog.csdn.net...

  • NSTimer 在子线程中添加到 使用 dateWithTime

    在写 NSTimer 和 NSRunLoop 的测试用例时,发现在子线程中创建的 NSTimer 添加到 使用 N...

  • IOS开发中NSRunloop跟NSTimer的问题

    IOS开发中NSRunloop跟NSTimer的问题 在Windows时代,大家肯定对SendMessage,Po...

  • NSRunLoopCommonModes

    1、NSTimer需要设置为NSRunLoopCommonModes模式[[NSRunLoop currentRu...

  • NSTimer

    一、NSTimer 运行条件 在一个NSRunloop 中的某个模式中运行,所在的runloop必须是运行的。 简...

  • NSTimer,NSRunLoop,autoreleasepoo

    引言 NSTimer内存泄漏真的是因为vc与timer循环引用吗?不是! 小伙伴们都知道,循环引用会造成内存泄漏,...

  • NSRunLoop和NSTimer

    一、什么是NSRunLoop NSRunLoop是消息机制的处理模式 NSRunLoop的作用在于有事情做的时候使...

  • NSRunloop跟NSTimer

    NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval...

网友评论

      本文标题:NSTimer中的NSRunloop

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