Using NSTimer is Swift causes 'deinit' not to call

1.6k views Asked by At

After using NSTimer, the class deinit method is never called. The class is written in Swift, and I call the timer at the "init" like so:

init(eventsDistributor : EventsDistributor, orderSide : ORDER_SIDE, stockViewModel : StockViewModel, orderType : ORDER_TYPE_ENUM, orderPrice : NSNumber) {
    self.eventsDistributor = eventsDistributor
    self.orderSide = orderSide
    self.stockViewModel = stockViewModel
    self.orderType = orderType
    self.orderPrice = orderPrice
    super.init()
    _events()
    loadPreOrderDetails()

    //Here I call the Timer:
    var reloadTimer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: "loadSecurityTradeInfo", userInfo: nil, repeats: true)
    reloadTimer.fire()        
}

I tried using the NSTimer as a local variable too, and no success there... Anyone facing this issue? Is there a timer I can use in Swift which will not causes the class not to be dealloced? Thanks

2

There are 2 answers

1
gnasher729 On BEST ANSWER

The timer has a strong reference to its target (self). And the target is scheduled to the run loop, which holds a strong reference to it until the timer is invalidated. Until you invalidate the timer (reloadTimer.invalidate, or probably from within the loadSecurityTradeInfo method), the object won't go away.

Which is actually very good, because the timer sending a loadSecurityTradeInfo message to the object would be a very, very bad idea after the object has gone.

loadSecurityTradeInfo should probably be changed to a method that takes a timer as an argument, so it can invalidate it.

2
Andrey Chernukha On

NSTimer retains its target. No surprise. You need to invalidate the timer first