Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Fix Error with a Swift NSTimer Calling Its Selector

I'm getting a runtime error of:

2014-07-15 16:49:44.893 TransporterGUI[1527:303] -[_TtC14TransporterGUI11AppDelegate printCountdown]: unrecognized selector sent to instance 0x10040e8a0

when I use the following Swift code to fire a timer:

@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

}

Oddly enough, if I change the signature of the function printCountdown to have no parameters, the function is called appropriately, but then I have no way of accessing the timer object that made the call.

Thanks in advance!

like image 961
P.M. Avatar asked Jul 15 '14 23:07

P.M.


1 Answers

Your selector should be "printCountdown:", with a terminating colon to indicate that the selector takes a parameter.

like image 144
Teo Sartori Avatar answered Nov 16 '22 02:11

Teo Sartori