Search code examples
iosswiftnstimer

Deinit is not called when assign NSTimer


This is how I declare property in my subclass of UIViewController:

private weak var timer: NSTimer?

This is what I do in viewDidLoad():

timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)

And this is my deinit:

deinit {
    timer?.invalidate()
    timer = nil
}

Deinit is not called because of NSTimer. Do not make funny telling that inside NSTimer there is a strong reference to my controller:) How can I workaround this?


Solution

  • I think that @i_am_jorf gave you a good direction. If you look at the documentation of invalidate method you will find a full explanation why it is acting like that

    This method is the only way to remove a timer from an NSRunLoop object. The NSRunLoop object removes its strong reference to the timer, either just before the invalidate method returns or at some later point.

    If it was configured with target and user info objects, the receiver removes its strong references to those objects as well.

    So yes, retain cycle created if invalidate not called in an appropriate moment