NSTimer timerWithTimeInterval 不调用选择器 (Swift)

NSTimer timerWithTimeInterval not calling selector (Swift)

我已经尝试了很多我在其他问题中发现的方法,并且它们中的任何一个都有效。我的问题是定时器没有调用 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()
        }

    }
}

我试过了

progressBarTimer.fire()

它只执行一次 updateProgress 函数。

谁能解释一下?非常感谢

您可以这样调用您的函数:

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

函数必须像这样:

func playProgressBar(timerSender : NSTimer) {

   //Do Somethings

}

回复自己,找到问题了。在之前的 ViewController 中,我在建立 http 连接后执行了一个 segue。为了让它工作,我在调度中嵌入了 performSegue:

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

在第二个控制器中,我有一个不工作的计时器。但是,此更改后工作正常。

感谢回复!