Swift Playground 中的 NSTimer.scheduledTimerWithTimeInterval [英] NSTimer.scheduledTimerWithTimeInterval in Swift Playground
问题描述
我看到的所有在 Swift 中使用NSTimer.scheduledTimerWithTimeInterval"的例子都使用了target: self"参数,但不幸的是,这不能直接在 Swift Playgrounds 中工作.
All the examples I've seen on using the "NSTimer.scheduledTimerWithTimeInterval" within Swift show using the "target: self" parameter, but unfortunately this doesn't work in Swift Playgrounds directly.
Playground execution failed: <EXPR>:42:13: error: use of unresolved
identifier 'self'
target: self,
这是上面引用的导致错误的示例:
Here's an example referenced above that results in the error:
func printFrom1To1000() {
for counter in 0...1000 {
var a = counter
}
}
var timer = NSTimer.scheduledTimerWithTimeInterval(0,
target: self,
selector: Selector("printFrom1To1000"),
userInfo: nil,
repeats: false
)
timer.fire()
推荐答案
这些天你真的不应该使用 NSTimer
.它会消耗大量资源,导致不必要的电池消耗,并且 API 会导致代码丑陋.
You really should not be using NSTimer
these days. It's consumes a lot of resources, causes unnecessary battery drain, and the API lends itself to ugly code.
使用 dispatch_after()
代替:
dispatch_after(0, dispatch_get_main_queue()) { () -> Void in
for counter in 0...1000 {
var b = counter
}
}
当然,由于计时器会在操场完成后触发,因此您需要等效于 timer.fire()
来强制代码立即执行,而不是在 0 秒延迟后执行.这是它的工作原理:
Of course, since the timer will fire after playground does it's stuff you will need an equivalent of timer.fire()
to force the code to execute immediately instead of after a 0 second delay. Here's how that works:
let printFrom1To1000 = { () -> Void in
for counter in 0...1000 {
var b = counter
}
}
dispatch_after(0, dispatch_get_main_queue(), printFrom1To1000)
printFrom1To1000()
这篇关于Swift Playground 中的 NSTimer.scheduledTimerWithTimeInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!