xcode 将参数传递给 Swift 中 NSTimer 调用的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24889279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing parameters to a method called by NSTimer in Swift
提问by Raghu
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.
我正在尝试将参数传递给由 NSTimer 在我的代码中调用的方法。它正在抛出异常。这就是我的做法。Circle 是我的自定义类。
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.
注意:该方法在调用它的同一个类中。所以我相信我已经正确设定了目标。
回答by Andy
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.
您使用的选择器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
}
回答by samullen
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:
您的选择器必须是一个字符串,除非它应该是一个 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
}
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.
我也看到包裹在“选择()”方法选择的字符串:Selector("animate")
。无论哪种方式都有效。
I've been messing with NSTimer
and closures myself and wrote an article on it: Using Swift's Closures With NSTimer
我自己一直在搞乱NSTimer
闭包,并写了一篇关于它的文章:使用 Swift 的闭包与 NSTimer