Passing parameters to a method called by NSTimer in Swift

大城市里の小女人 提交于 2019-11-26 12:33:40

问题


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.


回答1:


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
}



回答2:


Your selector needs to be a string unless that's supposed to be an ivar. Also, your animate function has the wrong signature. The following changes should get you moving again:

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

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

The function really doesn't need to return the empty tuple; it can be written without the -> ()

I've also seen the selector string wrapped in a "Selector()" method: Selector("animate"). It works either way.

I've been messing with NSTimer and closures myself and wrote an article on it: Using Swift's Closures With NSTimer



来源:https://stackoverflow.com/questions/24889279/passing-parameters-to-a-method-called-by-nstimer-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!