Ios Swift:使用带有多个参数的选择器
我试图在应用程序模型中保留一个NSTimer,并在视图控制器文件中更新时间。为此,我创建了以下两种方法:Ios Swift:使用带有多个参数的选择器,ios,swift,selector,Ios,Swift,Selector,我试图在应用程序模型中保留一个NSTimer,并在视图控制器文件中更新时间。为此,我创建了以下两种方法: func startTimer(labelToUpdate : UILabel) { timerGoing = true timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "decTimeByOne:labelToUpdate:", userInfo: labelToUpdate
func startTimer(labelToUpdate : UILabel) {
timerGoing = true
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "decTimeByOne:labelToUpdate:", userInfo: labelToUpdate, repeats: true)
}
func decTimeByOne(labelToUpdate : UILabel) {
if timerGoing {
if decreasingTime > 0 {
decreasingTime--;
labelToUpdate.text = "\(decreasingTime)"
}
else {
timerGoing = false
timer.invalidate()
}
}
}
我在控制台中遇到运行时异常(我相信),即存在“无法识别的选择器”。在做了一些研究之后,我的印象是这就是Swift中用来调用选择器中多个参数方法的语法:选择器:“methodName:argumentName:”,userInfo:argumentPassedIn
最后,我想保留一个与我的模型对象相关联的计时器,只需要在我的应用程序视图中更新和显示该时间。这是正确的方法吗?将所有内容存储在一个数组中,并将其传递给userInfo。然后你想传递什么就传递什么
func startTimer(labelToUpdate : UILabel) {
var array = [labelToUpdate, otherStuff]
timerGoing = true
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "decTimeByOne:", userInfo: array, repeats: true)
}
func decTimeByOne(labelToUpdate : UILabel) {
var array = labelToUpdate.userInfo
if timerGoing {
if decreasingTime > 0 {
decreasingTime--;
labelToUpdate.text = "\(decreasingTime)"
}
else {
timerGoing = false
timer.invalidate()
}
}
}
我的印象是,这是Swift中用来在选择器中调用多个参数方法的语法:`selector:'methodName:argumentName:'
在某种程度上,这是正确的,但这并不能免除您在使用NSTimer时阅读NSTimer上的文档的责任。特别是,它不会改变一个事实,即NSTimer调用的选择器不是由您决定的。它的形式只能是methodName:
,因为它只接受一个参数——计时器(而不是标签或其他任何参数)。正如您已经被告知的,如果您有其他信息要传递,请将其附加到计时器,这就是将要传递的信息
另外,关于如何声明方法的名称,您也错了。声明为
func decTimeByOne(labelToUpdate:UILabel
的方法的选择器是decTimeByOne:
。同样,这不取决于您;您必须知道如何创建选择器的规则。您的函数不是多参数函数。正确的选择器只是“decTimeByOne”: