iOS定时器NSTimer快速掌握


本文主要讲NSTimer。CADisplaylink请猛击。


NSTimer创建方式有三种:

⚠️:block方式可用为iOS(10.0)。低版本调用会崩溃。

  • 方式一
    [scheduledTimerWithTimeInterval:invocation:repeats:]
    [scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
    [scheduledTimerWithTimeInterval:repeats:repeatsblock:]⚠️API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

class method to create the timer and schedule it on the current run loop in the default mode.

Overview:这种方式创建会自动加入到Runloop的timerSource事件中。
注意的坑:

  1. 加入到Runloop的mode为NSDefaultRunLoopMode。而UI响应滚动事件<如滑动TableView>时的mode为UITrackingRunLoopMode。Runloop只会有一种mode运行。如果NSTimer在主线程下,此时如果定时器响应了事件,事件会被跳过。子线程不会响应UITrackingRunLoopMode
    坑2: 如果调用线程为子线程,需要调用[[NSRunLoop currentRunLoop]run]来启动子线程的Runloop。

  • 方式二
    [timerWithTimeInterval:invocation:repeats: ]
    [timerWithTimeInterval:target:selector:userInfo:repeats: ]
    [timerWithTimeInterval:repeats: block:]⚠️API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode:
method of the corresponding NSRunLoop object.)

Overview:这种方式必需要调用[addTimer:forMode: ]把timer加入到Runloop中。模式可选NSRunLoopCommonModesNSDefaultRunLoopMode
补充知识:NSDefaultRunLoopModeUITrackingRunLoopMode都具备commonMode属性。它们会自动加入NSRunLoopCommonModes中的modeItem事件。
So:NSRunLoopCommonModes不会受其他mode影响,一般选用这种模式。


  • 方式三
    [- initWithFireDate:interval:target:selector:userInfo:repeats:]
    [- initWithFireDate:interval:repeats:block:] ⚠️API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode:
method of the corresponding NSRunLoop object)

Overview::这种方式必需要调用[addTimer:forMode: ]把timer加入到Runloop中。模式选择参考方式二。
special:

  1. 这是-号方法。
  2. 可以指定FireDate。即启动定时器时间。

汇总:

  1. 如果你的定时器是repeats = YES,那要记得在不需要timer的时候调用-invalidate来释放定时器。
  2. 需要注意定时器所在的线程。timer不执行,看这点。
  3. 使用定时器需要注意创建方式,是否需要手动加入Runloop。timer不执行,看这点。
  4. 需要注意加入Runloop的mode。如果timer某次未执行,看这点。
  5. 如果你的token用这个,一定要注意,不然token失效就GG了。

Write In Last:
本文用到了一些Runloop知识。其实timer和runloop关系很大。推荐一个特别好的博文。记得点赞哦😄。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 基本概念 进程 进程是指在系统中正在运行的一个应用程序,而且每个进程之间是独立的,它们都运行在其专用且受保护的内存...
    小枫123阅读 928评论 0 1
  • 一、什么是NSRunLoop NSRunLoop是消息机制的处理模式 NSRunLoop的作用在于有事情做的时候使...
    呦释原点阅读 679评论 0 2
  • 一、什么是runloop 字面意思是“消息循环、运行循环”。它不是线程,但它和线程息息相关。一般来讲,一个线程一次...
    WeiHing阅读 8,179评论 11 111
  • ios 常用的定时器有三种:NSTime,CADisplayLink和GCD。 NsTimer // 参数:Int...
    殿小七阅读 863评论 0 2
  • 一、什么是RunLoop 基本作用: 保持程序的持续运行; 处理App中的各种事件(比如触摸事件、定时器事件、Se...
    magic_pill阅读 921评论 0 0