将参数传递给 NSTimer 在 Swift 中调用的方法
Posted
技术标签:
【中文标题】将参数传递给 NSTimer 在 Swift 中调用的方法【英文标题】:Passing parameters to a method called by NSTimer in Swift 【发布时间】:2014-09-13 09:15:31 【问题描述】:我正在尝试将参数传递给 NSTimer 在我的代码中调用的方法。它正在引发异常。我就是这样做的。 Circle 是我的自定义类。
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
注意:该方法与被调用的类在同一个类中。所以我相信我已经正确地设定了目标。
【问题讨论】:
【参考方案1】:与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
【讨论】:
两个参数怎么样? 将两个参数作为元组传递给 userInfo?或者制作一个封装两个参数的自定义结构?我现在不能尝试这个,也许这会给你一个提示。再次询问您是否仍然卡住【参考方案2】:您的选择器必须是一个字符串,除非它应该是一个 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
函数真的不需要返回空元组;不用-> ()
也可以写
我还看到选择器字符串包含在“Selector()”方法中:Selector("animate")
。无论哪种方式都可以。
我自己一直在搞乱NSTimer
和闭包,并写了一篇关于它的文章:Using Swift's Closures With NSTimer
【讨论】:
Xcode 中的字符串替换:@"bla bla"; Swift 中的字符串替换:“bla bla”所以这是正确的答案。 似乎仍然不起作用。我收到以下错误消息 *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:无法识别的选择器发送到实例 0x10da13d60' 无法传递circle参数,但看起来它已经是一个属性了。 try: func animate() //用 self.circle 做一些事情 这就是问题所在。我有很多需要定期动画的圆形对象。所以他们需要被传递到那个方法中selector: "animate"
应该是selector: "animate:"
。以上是关于将参数传递给 NSTimer 在 Swift 中调用的方法的主要内容,如果未能解决你的问题,请参考以下文章