Stop NSTimer and dismiss view controller (swift)

强颜欢笑 提交于 2019-12-01 12:04:21

Just store the instance of your timer and then when you are moving to another Controller invalidate the timer, so that first declare one instance of NSTimer.

var timer:NSTimer?

Now use this object to store the reference of your scheduledTimer.

self.timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(DriversInterfaceViewController.CheckFormularChild), userInfo: nil, repeats: true)

Now on moving to another controller simply.

self.timer.invalidate()
    var timer:NSTimer?

    timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: 
    #selector(DriversInterfaceViewController.CheckFormularChild), userInfo: nil, repeats: true)

    //ToStop Timer

    timer.invalidate()
    timer = nil

It's a good thing to nil the instance variable timer after having invalidated it, it avoids further confusion if you need to create another timer with the same variable.

// Hi, after timer event completion you need to invalidate that timer as like as follow

yourTimer.invalidate()

To cancel a NSTimer, just use:

timer?.invalidate()

And please make sure your function DriversInterfaceViewController.CheckFormularChild runs in UIThread (If this method touches UI) or else it'll crash

When the NSTimer haven't invalidate, the instance of view controller stayed in memory and haven't release in ARC. So you need to invalidate the NSTimer when the old view controller disappear.

override func viewWillDisappear(animated: Bool) 
{
   if self.timer != nil
   {
      self.timer!.invalidate()
      self.timer = nil
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!