使用 NSTimer (Swift) 时遇到问题 [英] Having trouble with NSTimer (Swift)
问题描述
--使用更新信息进行编辑--
--EDITED WITH UPDATED INFORMATION--
我想做的是使用 NSTimer.scheduledTimerWithTimeInterval
方法每五秒调用一次名为 timerFunc
的函数,问题似乎是在运行时,我得到错误
What I wish to do is call a function named timerFunc
once every five seconds using a NSTimer.scheduledTimerWithTimeInterval
method, the issue seems is that during runtime, I get the error
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-
[Animation.ViewController timerFunc:]: unrecognized selector sent to instance 0x7fe548d66040'
在输出日志中.我一直在寻找其他人的 NSTimers 无济于事,我看到很多选择器都是 selector: Selector("timerFunc:")
而不是 selector: Selector("timerFunc")
两种方式,但是,给出错误.另一件事是 timerFunc 函数和 NSTimer 都在 viewDidLoad 内,这有什么问题吗?非常感谢您对该问题的任何见解,感谢阅读.
In the output log. I've been looking up other people's NSTimers to no avail, I see quite a few have the selector as selector: Selector("timerFunc:")
instead of selector: Selector("timerFunc")
both ways, however, give the error. Another thing is that both the timerFunc function and the NSTimer are inside of viewDidLoad, are there any issues with that? Any insight on the problem is greatly appreciated, thanks for reading.
timerFunc 下面
timerFunc below
func timerFunc(){
println("Timer")
}
下面的NSTimer
NSTimer.scheduledTimerWithTimeInterval(
5.0,
target: self,
selector: Selector("timerFunc"),
userInfo: nil,
repeats: true)
推荐答案
另外一个问题是 timerFunc 函数和 NSTimer 都在 viewDidLoad 里面,有什么问题吗?
是的.那是你的问题.timerFunc
不能嵌套在 viewDidLoad
内部,它必须是与 viewDidLoad
处于同一级别的顶级函数.
Yes. That is your problem. The timerFunc
can't be nested inside of viewDidLoad
, it must be a top level function at the same level as viewDidLoad
.
class ViewController: UIViewController {
override func viewDidLoad() {
....
NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "timerFunc", userInfo: nil, repeats: true)
}
func timerFunc() {
println("Timer")
}
}
当定时器触发时,它会在目标指定的对象上调用选择器指定的函数.也就是说,它将调用 self.timerFunc()
.当您的 timerFunc()
嵌套在 ViewDidLoad
内时,它找不到它.
When the timer fires, it will call the function specified by the selector on the the object designated by target. That is, it will call self.timerFunc()
. When your timerFunc()
is nested inside of ViewDidLoad
, it can't find it.
这篇关于使用 NSTimer (Swift) 时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!