Search code examples
iosswiftselectornstimeruserinfo

UserInfo in NSTimer not passing correct information - Swift


Here is some sample code for what I am trying to do.

func firstFunction() {
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: Selector("secondFunction:"), userInfo: self.data!.getInfo(), repeats: false);
    println("Info: \(timer.userInfo)");
}

func secondFunction(value: Int) {
    println("Called with \(value)");
}

The following is the output: Info: Optional(( 2 )) and Called with 140552985344960

Called with ############ is constantly changing too. Even if I use just a number in place of self.data!.getInfo I still get Info: Optional(2) as the output and the Called with output still changes. I'm thinking it's happening because the value being passed is an optional one, so how do I make it not optional if that is the problem?


Solution

  • NSTimer's scheduledTimerWithTimeInterval userInfo parameter is not a standard parameter in the sense that although you can set userInfo to hold AnyObject, you can't simply pass in a parameter as you would with most functions because scheduledTimerWithTimeInterval's selector can only be passed an NSTimer as its one and only parameter. So your secondFunction: must specify an NSTimer as its parameter if you'd like to access the value you have stored within the timer's userInfo, ex:

    func firstFunction() {
        var timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: Selector("secondFunction:"), userInfo: self.data!.getInfo(), repeats: false);
        println("Info: \(timer.userInfo)");
    }
    
    func secondFunction(timer: NSTimer) {
        var value = timer.userInfo as Int
        secondFunction(value)
    }
    
    // Function added based on your comment about
    // also needing a function that accepts ints
    func secondFunction(value: Int) {
        println("Called with \(value)");
    }