使dealloc中的NSTimer无效 [英] Invalidating an NSTimer in dealloc

查看:177
本文介绍了使dealloc中的NSTimer无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题之后,更具体地说,此评论



b 因为在常见情况下,定时器的目标也是其所有者,retain(aka强引用)循环


我想知道为什么 dealloc 不是使 NSTimer 无效的好地方。



我记得我的应用程序没有自动重复 NSTimer 无效,然后在 dealloc ,并且正确释放内存。



dealloc / p>

事实上你的重写 dealloc 之前调用任何 NSObject deallocation?什么是 dealloc 甚至用于,然后?如果不是手动释放相应对象的属性?

解决方案

ARC只会释放(并调用 dealloc $ )对象,当没有 strong 引用指向这个对象(没有人保留)。



NSTimer 创建 strong 引用,它将保留 target



这意味着, dealloc 将不会被调用,因为NSTimer仍然具有 strong 对象的引用。如果没有 dealloc ,这意味着 NSTimer 永远不会被无效...导致内存泄漏甚至崩溃。



有一种方法无效定时器在 dealloc 或当 target 变为nil时。请查看此处的答案。


Following this question, and more specifically, this comment:

because retain (aka strong reference) cycles in the common case where the timer's target is also its owner

I am wondering why dealloc isn't a good place to invalidate an NSTimer.

I remember profiling my app without auto-repeating NSTimer invalidation and then with invalidation in dealloc, and the memory correctly freed.

Is dealloc working differently in the latest iOS?

Isn't in fact your overridden dealloc called prior to any NSObject deallocation? What is dealloc even used for, then? If not manually deallocating the respective object's properties?

解决方案

ARC will only release ( and call dealloc ) objects, when there are no strong references pointing to this object ( no one is retaining ).

NSTimer creates strong reference and it will retain target.

This means, dealloc will not be called, because NSTimer still has strong reference to the object. If there is no dealloc, this means NSTimer will never be invalidated ... leads to memory leak or even crashes.

There is a way to invalidate timer in dealloc or when target becomes nil. Have a look at the answer here.

这篇关于使dealloc中的NSTimer无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆