Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to a method called by NSTimer in Swift

Tags:

I'm trying to pass an argument to a method that is called by NSTimer in my code. It is throwing an exception. This is how I'm doing it. Circle is my custom class.

    var circle = Circle()     var timer = NSTimer.scheduledTimerWithInterval(1.0, target: self, selector: animate, userInfo: circle, repeats: true) 

Below is the method that is being called

    func animate(circle: Circle) -> Void{       //do stuff with circle     } 

Note: The method is in the same class that it is being called. So I believe i've set the target correctly.

like image 919
Raghu Avatar asked Jul 22 '14 13:07

Raghu


1 Answers

The selector you use with NSTimer is passed the NSTimer object as it's one and only parameter. Put the circle object in it as userInfo and you can extract it when the timer fires.

var circle = Circle() var timer = NSTimer.scheduledTimerWithInterval(1.0, target: self, selector: "animate:", userInfo: circle, repeats: true)  func animate(timer:NSTimer){   var circle = timer.userInfo as Circle   //do stuff with circle } 
like image 109
Andy Avatar answered Oct 19 '22 03:10

Andy