NSTimer,即计时器,用于定时执行一些任务,一次或者多次。

系统Foundation框架提供的最常用方法如下,创建一个NSTimer,并将它放到当前runloop的default mode中。

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti // 执行任务的时间间隔
                      target:(id)aTarget // 执行任务的对象
                     selector:(SEL)aSelector // 执行任务的对象方法
                     userInfo:(nullable id)userInfo // 用于传一些参数
                     repeats:(BOOL)yesOrNo; // 是否重复执行

1、怎么保证在未来某个时间点,要执行任务时,target还有效呢?target完全有可能被释放了呀。鉴于此,NSTimer会持有target对象,直到NSTimer invalidate。不同的是,一次性NSTimer会在执行完任务之后,会自动invalidate;而重复性NSTimer,则需要手动invalidate,否则会造成内存泄漏。

2、由于NSTimer会持有target对象,如果刚好target对象就是self,而NSTimer又是self的一个实例变量,就会引发循环引用:self->NSTimer->self。

@interface TimerTest () {
NSTimer *_timer; // self持有_timer
} @end @implementation TimerTest - (id)init
{
if (self = [super init]) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(test) userInfo:nil repeats:YES]; // _timer持有self
}
return self;
} - (void)dealloc
{
// 因为_timer持有self,所以self的引用计数>=1,也就执行不到dealloc。
[_timer invalidate]; // 而执行不到dealloc,这句也就执行不到,_timer会一直持有self。这时候只能其他地方将_timer invalidate才行。
} - (void)test
{ } @end

为了解决这种循环引用问题,主要有两种方法:

1)实现一个NSTimer的category,并提供block接口。

@implementation NSTimer (Safe)

+ (NSTimer *)safeScheduledTimerWithTimeInterval:(NSTimeInterval)interval
repeats:(BOOL)repeats
blk:(void(^)())blk {
return [self scheduledTimerWithTimeInterval:interval
target:self // target变成了NSTimer类对象,类对象由系统自动回收
selector:@selector(_doBlock:) // NSTimer会把自己传过去
userInfo:[blk copy] // 把block拷贝到堆上,避免栈block到用时已经被回收了
repeats:repeats];
} + (void)_doBlock:(NSTimer *)timer {
void(^blk)() = timer.userInfo;
if(blk) {
blk();
}
} @end @interface TimerTest () {
NSTimer *_timer; // self持有_timer
} @end @implementation TimerTest - (id)init
{
if (self = [super init]) {
__weak TimerTest *weakSelf = self;
_timer = [NSTimer safeScheduledTimerWithTimeInterval: repeats:YES blk:^{
__strong TimerTest *strongSelf = weakSelf;
[strongSelf test];
}];
}
return self;
} - (void)dealloc
{
[_timer invalidate];
} - (void)test
{ } @end 

3、NSTimer必须放在runloop中才能生效。如下方法就只是创建一个NSTimer,而并没有把它放到runloop中。

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

需要调用如下方法把它放到runloop中,才能生效。

- (void)addTimer:(NSTimer *)timer forMode:(NSRunLoopMode)mode;

https://developer.apple.com/documentation/foundation/nstimer/2091889-scheduledtimerwithtimeinterval

NSTimer深入理解的更多相关文章

  1. iOS开发中深入理解CADisplayLink和NSTimer

    一.什么是CADisplayLink 简单地说,它就是一个定时器,每隔几毫秒刷新一次屏幕. CADisplayLink是一个能让我们以和屏幕刷新率相同的频率将内容画到屏幕上的定时器.我们在应用中创建一 ...

  2. 关于NSRunLoop和NSTimer的深入理解

    一.什么是NSRunLoop NSRunLoop是消息机制的处理模式 NSRunLoop的作用在于有事情做的时候使的当前NSRunLoop的线程工作,没有事情做让当前NSRunLoop的线程休眠 NS ...

  3. 深入理解CADisplayLink和NSTimer

    一.什么是CADisplayLink 简单地说,它就是一个定时器,每隔几毫秒刷新一次屏幕. CADisplayLink是一个能让我们以和屏幕刷新率相同的频率将内容画到屏幕上的定时器.我们在应用中创建一 ...

  4. 深入理解RunLoop

    网上看的一篇文章,写的真好,我得多看几次好好理解理解 膜拜大神,转载至此便于学习查看. 此处标明原文链接:http://blog.ibireme.com/2015/05/18/runloop/    ...

  5. iOS开发——高级篇——iOS 中的 NSTimer

    以前的老代码在使用 NSTimer 时出现了内存泄露 NSTimer fire 我们先用 NSTimer 来做个简单的计时器,每隔5秒钟在控制台输出 Fire .比较想当然的做法是这样的: 1 2 3 ...

  6. __block 与 __weak的区别理解

    Blocks理解: Blocks可以访问局部变量,但是不能修改 如果修改局部变量,需要加__block __block int multiplier = 7; int (^myBlock)(int) ...

  7. Swift: 深入理解Core Animation(一)

    如果想在底层做一些改变,想实现一些特别的动画,这时除了学习Core Animation之外,别无选择. 最近在看<iOS Core Animation:Advanced Techniques&g ...

  8. RunLoop机制理解

    一.浅识RunLoop RunLoop在开发中我们一直在用,但是没有注意他.要想理解RunLoop,首先我们需要先了解一下程序运行机制. 程序运行机制:我们都知道OC是运行时语言,也就是说对象的类型是 ...

  9. IOS开发中NSRunloop跟NSTimer的问题

    在Windows时代,大家肯定对SendMessage,PostMessage,GetMessage有所了解,这些都是windows中的消息处理函数,那对应在ios中是什么呢,其实就是NSRunloo ...

随机推荐

  1. Linux下编译、链接和装载

    ——<程序员的自我修养>读书笔记 编译过程 在Linux下使用GCC将源码编译成可执行文件的过程可以分解为4个步骤,分别是预处理(Prepressing).编译(Compilation). ...

  2. sql server: quering roles, schemas, users,logins

    --https://docs.microsoft.com/en-us/sql/relational-databases/security/authentication-access/managing- ...

  3. 【读书笔记】iOS-xib,点击事件的连接(三)

    紧接着上一节来写 一,选中On按钮,同时按住Control键,连接到FirstViewController.h文件中. 会弹出如下对话框. 二,将Connection处选择为Action,同时将Nam ...

  4. 限制Apache日志access.log、error.log文件大小

    在 Windows 下的设置例子如下: # 限制错误日志文件为 1M ErrorLog "|bin/rotatelogs.exe -l logs/error-%Y-%m-%d.log 1M& ...

  5. SD从零开始65 框架协议(Outline Agreement)

    SD从零开始65 框架协议(Outline Agreement) 合同-销售凭证类型Contracts-Sales Document Types 框架协议在几乎所有的业务处理中都扮演重要的角色:客户和 ...

  6. NopCommerce 根据手机浏览器和桌面浏览器切换 Theme

    自从 NopCommerce 升级到 3.x 以来,默认的 ViewName.Mobile.cshtml 方式就被响应式的默认 Theme 取代了. 但是在今天各种手机专用前端库大行其道的情况下,响应 ...

  7. centos 7.2 64位 docker安装lamp环境

    1. 删除docker可能有的早期版本 yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docke ...

  8. NFS常见问题

    问题一:取消挂载失败 问题现象: umount /opt/data umount.nfs: /opt/data: device is busy umount.nfs: /opt/data: devic ...

  9. 【16】有关python面向对象编程

    面向对象编程 一.第一个案例---创建类 #__author:"吉" #date: 2018/10/27 0027 #function: # 设计类: ''' 1 类名:首字母大写 ...

  10. IDEA设置注释的颜色

    IDEA默认的灰色注释确实让人看不清,但如果把灰色调成黑色又和代码的颜色相同了,所以,不如给注释添加上绿色的背景,又护眼又容易分辨 新版本的IDEA打开Settings——Editot——Color ...