[英]Can I use didSet in deinit?
I added a variable of Timer to my class, and used its didSet observer to invalidate old value 我在我的类中添加了一个Timer变量,并使用其didSet观察器使旧值无效
var timer: Timer? {
didSet { oldValue?.invalidate() }
}
deinit {
timer = nil
}
I thought this would be enough to invalidate timer when class is deinitialized, but looks like didSet is not called. 我认为这样就足以在类被取消初始化时使计时器无效,但看起来似乎没有调用didSet。 Why is that?
这是为什么? Are observers not working during deinitialization?
观察员在去初始化期间不工作吗?
Let's put an answer here so we can close this off. 我们在这里给出答案,以便我们可以关闭它。
It seems that property observers apparently do not run during deinit
. 看来物业观察员显然不会在
deinit
期间deinit
。 This seems parallel to the fact that property observers do not run during init
, but unlike the latter, the former doesn't seem to be clearly documented anywhere. 这似乎与属性观察者在
init
期间不运行这一事实相似,但与后者不同,前者似乎没有在任何地方清楚地记录。
You can work around this by semantic trickery, but don't! 你可以通过语义技巧解决这个问题,但不要! That seems like a bug (and I've filed it).
这似乎是一个错误(我已经提交了)。
The original use case was not a very good one to begin with. 最初的用例并不是一个非常好的用例。 Hiding invalidation of a timer in replacement sounds like a potential maintenance nightmare.
在替换中隐藏计时器的失效听起来像是潜在的维护噩梦。 Agreed that invalidation and replacement go together like ham and eggs, what I always do is write a method that invalidates and replaces, in that order, and funnel everything through that method.
同意失效和替换像火腿和鸡蛋一样,我一直在做的是编写一种方法,按照这个顺序使一切无效并替换,并通过该方法汇集所有内容。 (This can be enforced if necessary, but I won't go into that.) That method can be called during
deinit
. (如果需要,可以强制执行,但我不
deinit
。)可以在deinit
期间调用该方法。
SUPPLEMENTARY NOTE : Watch out, when using a timer, for memory management issues! 补充说明 :在使用计时器时,请注意内存管理问题! You can easily get yourself into a situation where
deinit
is never called, because you're retaining the timer but the timer is retaining you. 您可以轻松地让自己进入一个从未调用过
deinit
的情况,因为您保留了计时器,但计时器正在保留您。 You will then fail to invalidate the timer and your entire view controller will leak. 然后,您将无法使计时器无效,并且您的整个视图控制器将泄漏。 You don't complain about that in your question, but it's a related matter so I thought I'd better flag it.
你不会在你的问题中抱怨这一点,但这是一个相关的问题,所以我认为我会更好地标记它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.