Passing parameters to a method called by NSTimer in Swift

后端 未结 2 1303
梦谈多话
梦谈多话 2020-11-29 13:00

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.

2条回答
  •  失恋的感觉
    2020-11-29 13:40

    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
    }
    

提交回复
热议问题