NSTimer timerWithTimeInterval not calling selector

2019-09-14 19:17发布

问题:

I have tried many approaches that I have found in other questions and any of them are working. My problem is that the timer is not calling selector

class MyViewController: UIViewController{
    var progressBarTimer = NSTimer()
    @IBOutlet weak var progress_bar: UIProgressView!

    override func viewDidLoad() {
        self.progress_bar.progress = 0
        self.progressBarTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(MyViewController.updateProgress(_:)), userInfo: nil, repeats: true)
        //also tried and redefining the updateProgress without timer parameter:
        /*
        *self.progressBarTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(MyViewController.updateProgress), userInfo: nil, repeats: true)
        */
    }
    func updateProgress(timer:NSTimer!) {
        progress_bar.progress += 0.1
        if (progress_bar.progress >= 1) {
           progressBarTimer.invalidate()
        }

    }
}

I have tried to do

progressBarTimer.fire()

and it just executes once the updateProgress function.

Could anyone shed light on? I would really appreciate

回答1:

You can call your function like this:

    let postes = ["1","2","3"]
    let timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "playProgressBar:", userInfo: postes, repeats: true)

and function must like this:

func playProgressBar(timerSender : NSTimer) {

   //Do Somethings

}


回答2:

Replying to myself, I have found the problem. In the previous ViewController I am performing a segue after doing a http connection. In order to make it work, I have embedded the performSegue inside the dispatch:

dispatch_async(dispatch_get_main_queue(), {
    self.performSegueWithIdentifier("goMySecondController", sender: nil)
})

In that second Controller is where I have the Timer that was not working. However, after this change is working properly.

Thanks for replies!