swiftdeinitproperty-observer

Can I use didSet in deinit?


I added a variable of Timer to my class, and used its didSet observer to invalidate old value

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. Why is that? Are observers not working during deinitialization?


Solution

  • Let's put an answer here so we can close this off.

    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. 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.