jianxing798 jianxing798 - 1 year ago 99
Swift Question

deinit cannot call the function

i want use the deinit release a

,but it cant work. i want to know how to use the


class timerView: NSObject {
var timer:NSTimer?
override init() {
self.timer = NSTimer(fireDate: NSDate(), interval: 1, target: self, selector: "timers", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSDefaultRunLoopMode)
self.timer = nil

func timers() -> Void {

var timeV:timerView?
override func viewDidLoad() {
self.timeV = timerView()
self.timeV = nil

Answer Source

You can just invalidate the timer:


From NSTimer Class Reference:

... Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes the timer (and the strong reference it had to the timer), either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.

Which is exactly what you are trying to do when calling dinit.

**Since the answer is not satisfactory, I can try and guess your issue: you created the timer in a class, but maybe tried to invalidate the timer from different spot in your program. But is dosen't work becuase:

you should always call the invalidate method from the same thread on which the timer was installed.

A possible solution to such situation will be to hold the timer in it's own struct:

struct programTimer {
  static var timer: NSTimer = NSTimer()