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. 【CSS学习】--- 背景

    一.前言 元素的背景区域包括:元素的内容.内边距和边框区域. CSS中用于设置背景的属性有: background-color 设置背景颜色 background-image 设置背景图片 backg ...

  2. postgresql-10.1-3-windows-x64 安装之后,起动pgAdmin 4问题(win10)

    运行pgAdmin出现”pgAdmin 4  the application server could not be contant“ 窗口. 参考:https://stackoverflow.com ...

  3. DOM事件-调用函数

    通过调用函数改变其内容: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> ...

  4. 1474 十进制转m进制

    1474 十进制转m进制  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 白银 Silver 题解       题目描述 Description 将十进制数n转换成m进制数 m ...

  5. 【工具相关】Web-ionic-npm的安装

    一, 一般最新版本的Node.js集悲剧了npm.在命令行下,输入命令: "npm-v",可以测试npm是否安装.如下图所示: 二,上图显示了npm的版本号,即代表已经安装了npm ...

  6. 【PAT】B1082 射击比赛(20 分)

    水提水题,直接贴代码啦 #include<cstdio> #include<algorithm> using namespace std; struct ppp{ int id ...

  7. Django之Template

    模板层(template) 概念:  模板与html的区别:  模板=html+模板语法 模板语法: 1 变量:       {{}}    深度查询: 通过句点符.    列表,字典    clas ...

  8. Linux基础第四课——文件操作

    文件的创建 touch sudo touch 文件1 文件2 文件3 #支持批量创建文件 sudo rm -f 文件1 文件2 文件3 #支持批量创建 也支持批量删除 echo '谁动谁输,对不起我输 ...

  9. Python3中PyMongo的用法

    MongoDB存储 在这里我们来看一下Python3下MongoDB的存储操作,在本节开始之前请确保你已经安装好了MongoDB并启动了其服务,另外安装好了Python的PyMongo库. 连接Mon ...

  10. mysql删除数据左右空格

    select trim(字段) from 表 删除左右空格 select ltrim(字段) from 表 删除左空格 select rtrim(字段) from 表 删除右空格