Search code examples
swiftnstimer

how to pass a integer variable argument to the NSTimer calling function


I would like to pass an variable having a integer value into a function while NSTimer calls that function

func work()
{
    var x= 10
    var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "Disp", userInfo: x , repeats: false)
}

    func Disp(timer:NSTimer)
    {
       //access the x value
       print("\(x)")
    }

But the userinfo part takes only arguments of types objects(AnyObject?). Please some one help me. Also the variable x should not be declared globally as x is a local variable and its value is assigned during runtime dynamically inside a method for my original need.

This is my exact situation. Please help me friends. Thanks in advance.


Solution

  • you can pass the value in user info while calling the NSTimer,when your Disp function will be called you can get the value from timer user info

     func work()
        {
            var x = 10
            var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "Disp:", userInfo: x , repeats: false)
        }
    
    
        func Disp(timer:NSTimer)
        {
            //access the x value
            print("\(timer.userInfo)")
        }