如何使用Swift NSTimer调用其选择器来修复错误

P.M*_*.M. 5 parameters runtime-error nstimer swift

我收到运行时错误:

2014-07-15 16:49:44.893 TransporterGUI [1527:303] - [_ TtC14TransporterGUI11AppDelegate printCountdown]:无法识别的选择器发送到实例0x10040e8a0

当我使用以下Swift代码来触发计时器时:

@IBAction func schedule(sender : AnyObject) {

    var startTime = startDatePicker.dateValue.timeIntervalSinceDate(NSDate())
    var endTime = endDatePicker.dateValue.timeIntervalSinceDate(startDatePicker.dateValue)
    var startDate = NSDate.date()
    let params = ["startTime": startTime, "startDate": startDate]

    var counter = NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, selector:Selector("printCountdown"),
        userInfo:params, repeats:true)
}

func printCountdown(timer: NSTimer) {

    var userInfo = timer.userInfo as NSDictionary
    var startTime = userInfo["startTime"] as NSTimeInterval
    var startDate = userInfo["startDate"] as NSDate

    var elapsedTime: NSTimeInterval = NSDate.date().timeIntervalSinceDate(startDate)
    var remainingTime: NSTimeInterval  =  startTime - elapsedTime;

    if (remainingTime <= 0.0) {
        timer.invalidate()
        transferLabel.title = "No transfer scheduled"
    }

    transferLabel.title = remainingTime.description

}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,如果我将函数printCountdown的签名更改为没有参数,则会正确调用该函数,但是我无法访问进行调用的计时器对象.

提前致谢!

Teo*_*ori 6

您的选择器应为"printCountdown:",带有终止冒号以指示选择器采用参数.