本文介绍了将参数传递给Swift中由NSTimer调用的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将参数传递给我的代码中由NSTimer调用的方法。这是一个例外。这就是我的做法。 Circle是我的自定义类。
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)
以下是方法被称为
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.
推荐答案
与 NSTimer一起使用的选择器
传递 NSTimer
对象,因为它是唯一的参数。将圆形对象放在 userInfo
中,然后在计时器触发时将其解压缩。
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
}
这篇关于将参数传递给Swift中由NSTimer调用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!