Stop NSTimer and dismiss view controller (swift)

左心房为你撑大大i 提交于 2019-12-01 10:49:18

问题


I am using NSTimer to look for updates in my firebase database. I have put the code inside my viewDidLoad().

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

When the user has received a file in the database I want the user to goto another ViewController. The problem is that either the old ViewController is running in the background or the timer does not stop when changing View Controller.

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)            
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("recievedMission") as! RecievedMissionViewController
self.navigationController!.pushViewController(nextViewController, animated: true)

How do I dismiss the old View Controller or how do I stop the NSTimer programmatically? Thanks!


回答1:


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()



回答2:


    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.




回答3:


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

yourTimer.invalidate()



回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/39528337/stop-nstimer-and-dismiss-view-controller-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!