在 dealloc 中使 NSTimer 失效

Invalidating an NSTimer in dealloc

正在关注 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

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

我记得在没有自动重复 NSTimer 失效的情况下分析我的应用程序,然后在 dealloc 中进行失效,并且正确释放了内存。

dealloc 在最近的 iOS 中工作方式是否不同?

实际上您的重写 dealloc 不是在任何 NSObject 释放之前调用的吗?那么 dealloc 到底是用来做什么的呢?如果不手动解除分配相应对象的属性?

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

NSTimer 创建 strong 引用并将保留 target.

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

有一种方法可以在 dealloctarget 变为 nil 时 invalidate 计时器。看看 answer here.