简单的 NSTimer 实现问题
Simple NSTimer implementation issue
我刚刚开始学习 swift 2,我正在 Xcode 'playground' 中测试一些东西。当创建 'pyx' 的实例(如下)时,我没有看到我期望的控制台输出。我确定我犯了一个愚蠢的错误,但盯着它看了一会儿我还是想不通。
class zxy {
var gameTimer = NSTimer()
var counter = 0
init() {
gameTimer = NSTimer (timeInterval: 1, target: self, selector: "Run:", userInfo: nil, repeats: true)
}
func Run(timer : NSTimer) {
while(counter < 10){
print(counter)
counter++
}
timer.invalidate()
}
}
在此先致谢。
您已经创建了一个 NSTimer 对象,但这并没有启动计时器 - 只是让它准备就绪。使用 scheduledTimerWithTimeInterval 创建并启动计时器。
您的代码有 2 个问题。正如@glenstorey 在他的回答中指出的那样,您需要调用方法 scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
,而不是您正在调用的 init 方法。
编辑:
正如@DanBeauleu 在他对我的回答的评论中所说,电话在 Swift 中看起来像这样:
NSTimer.scheduledTimerWithTimeInterval(
1,
target: self,
selector: "Run:",
userInfo: nil,
repeats: true)
第二个问题是你的运行方法。
您不需要 while 循环。这将在计时器第一次触发时在一秒钟内重复 10 次,然后使计时器无效。
您的计时器方法需要更改为:
func Run(timer : NSTimer)
{
if counter < 10
{
print(counter)
counter++
}
else
{
timer.invalidate()
}
}
(顺便说一句,按照严格的约定,method/function 名称应以小写字母开头,因此您的 Run
函数应命名为 run
。)
我刚刚开始学习 swift 2,我正在 Xcode 'playground' 中测试一些东西。当创建 'pyx' 的实例(如下)时,我没有看到我期望的控制台输出。我确定我犯了一个愚蠢的错误,但盯着它看了一会儿我还是想不通。
class zxy {
var gameTimer = NSTimer()
var counter = 0
init() {
gameTimer = NSTimer (timeInterval: 1, target: self, selector: "Run:", userInfo: nil, repeats: true)
}
func Run(timer : NSTimer) {
while(counter < 10){
print(counter)
counter++
}
timer.invalidate()
}
}
在此先致谢。
您已经创建了一个 NSTimer 对象,但这并没有启动计时器 - 只是让它准备就绪。使用 scheduledTimerWithTimeInterval 创建并启动计时器。
您的代码有 2 个问题。正如@glenstorey 在他的回答中指出的那样,您需要调用方法 scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
,而不是您正在调用的 init 方法。
编辑:
正如@DanBeauleu 在他对我的回答的评论中所说,电话在 Swift 中看起来像这样:
NSTimer.scheduledTimerWithTimeInterval(
1,
target: self,
selector: "Run:",
userInfo: nil,
repeats: true)
第二个问题是你的运行方法。
您不需要 while 循环。这将在计时器第一次触发时在一秒钟内重复 10 次,然后使计时器无效。
您的计时器方法需要更改为:
func Run(timer : NSTimer)
{
if counter < 10
{
print(counter)
counter++
}
else
{
timer.invalidate()
}
}
(顺便说一句,按照严格的约定,method/function 名称应以小写字母开头,因此您的 Run
函数应命名为 run
。)