将参数传递给Swift中由NSTimer调用的方法

Rag*_*ghu 20 xcode nstimer ios swift

我正在尝试将参数传递给我的代码中由NSTimer调用的方法.这是一个例外.这就是我的做法.Circle是我的自定义类.

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

下面是被调用的方法

    func animate(circle: Circle) -> Void{
      //do stuff with circle
    }
Run Code Online (Sandbox Code Playgroud)

注意:该方法与调用它的类相同.所以我相信我已经正确设定了目标.

And*_*ndy 38

您使用的选择器NSTimer将传递给NSTimer对象,因为它是唯一的参数.将圆形对象放入其中userInfo,您可以在计时器触发时将其提取出来.

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
}
Run Code Online (Sandbox Code Playgroud)


sam*_*len 0

你的选择器必须是一个字符串,除非它应该是一个 ivar。另外,您的animate函数签名错误。以下更改应该会让您再次行动起来:

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
}
Run Code Online (Sandbox Code Playgroud)

该函数实际上不需要返回空元组;它可以写成没有-> ()

我还看到了包裹在“Selector()”方法中的选择器字符串:Selector("animate")。无论哪种方式都有效。

我自己一直在搞乱NSTimer闭包,并写了一篇关于它的文章:Using Swift's Closures With NSTimer