关于NSTimer使用的内存泄漏问题之主线程

关于NSTimer的使用我一直处于模棱两可的状态,刚好近期项目中用到NSTimer,所以整理了一些注意事项并分享给大家,如果有不对的地方希望大家能够及时指正,谢谢。

一共写了两篇文章,另一篇是《关于NSTimer使用的内存泄漏问题之子线程》

使用方法这里不再做介绍了,网上的文章很多,同时本文的结尾也推荐了两篇不错的文章供大家参考。

因为在使用过程中,我们碰见最多问题就是内存泄漏问题。本文的主要核心就是围绕内存泄漏问题展开的。

注:本文讨论皆默认为在主线程下,且target为ViewController;本文没有引用循环引用的概念,因为我认为在NSTimer的使用中,产生内存泄漏的原因是没有处理NSTimer与线程以及其线程内runloop的关系,并不是weak or strong的问题。
  • NSTimer运行原理的简单介绍
  • 内存泄漏如何产生的
  • 什么情况下不会内存泄漏
  • 如何解决内存泄漏的问题

Part 1. NSTImer运行的简单介绍

  • 其实NSTimer的运行原理很简单,就是两个因素:1.添加到runloop中;2.开启runloop。

  • scheduledTimerWith方法是创建并加入到当前的runloop中,所以创建时不需要再次添加到当前线程中,如果在主线程创建则可以直接跑起来(因为主线程的runloop是默认开启的),在子线程的话需要手动开启runloop。

  • timerWith则需手动加入runloop,如果在子线程创建,还需要手动开启当前子线程的runloop(因为子线程不会自动开启runloop)。

Part 2. 内存泄漏如何产生的

前提:当我们不使用block的方式,并且repeats == YES。

当timer加入到runloop后,runloop会持有timer,timer会保留其target对象也就是持有target 。


持有关系.jpg

所以不管用weak还是strong,timer对target都是强引用的,如果没有办法实现弱引用target,那么就必须要通过先释放timer才能够释放target。

所以在dealloc方法中去[timer invalidate],都会造成内存泄漏,无法释放。因为invalidate的作用是将timer从runloop中移除,而target需要等待timer被移除后才能够解除timer对自己的持有,才可以走dealloc,所以这种情况下,不能在dealloc中invalidate。

解决方案:一般情况下可以在viewWillDisappear或viewDidDisappear中释放,可以解除对target的持有,释放target。

Part 3. 什么情况下不会内存泄漏

刚才在第2点中提到了一个前提,这个前提就是不会发生内存泄露的情况,分为以下两种情况。

1. 通过block接口,这是苹果提供的api,为了防止循环引用,但需要iOS10.0以后的版本。
image.png
/// Creates and returns a new NSTimer object initialized with the specified block object. This timer needs to be scheduled on a run loop (via -[NSRunLoop addTimer:]) before it will fire.
/// - parameter:  timeInterval  The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead
/// - parameter:  repeats  If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
/// - parameter:  block  The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

/// Creates and returns a new NSTimer object initialized with the specified block object and schedules it on the current run loop in the default mode.
/// - parameter:  ti    The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead
/// - parameter:  repeats  If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
/// - parameter:  block  The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

/// Initializes a new NSTimer object using the block as the main body of execution for the timer. This timer needs to be scheduled on a run loop (via -[NSRunLoop addTimer:]) before it will fire.
/// - parameter:  fireDate   The time at which the timer should first fire.
/// - parameter:  interval  The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead
/// - parameter:  repeats  If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
/// - parameter:  block  The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
2. repeats == NO,此时timer也不会持有target。

Part 4. 如何解决内存泄漏的问题

#pragma mark 1.不需要重复操作,repeats == NO(其实就是起一个可控的延时操作的作用)
// 当timer执行完任务后,系统会自动从当前线程中移除timer,所以不需要手动处理

#pragma mark 2.需要重复操作,即repeats == YES
/*
 * 首推block方式。虽然iOS原生api接口提供的block方式目前仅支持iOS10以后的版本,但不用担心,
   YYKit已经写好了替代方式,在YYKit中的NSTimer分类NSTimer_YYAdd中有block方法。
   只需在dealloc中[timer invalidate]即可。
*/
- (void)dealloc {
    [self.timer invalidate];
}
// 如果你习惯用非block的方式,那么就不能在dealloc中invalidate,如Part 2提到的解决方案.
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}
// 或
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}

参考文章:
《IOS定时器操作和NSTimer的各种坑》
《NSTimer的使用》

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,340评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,762评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,329评论 0 329
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,678评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,583评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,995评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,493评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,145评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,293评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,250评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,267评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,973评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,556评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,648评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,873评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,257评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,809评论 2 339