[英]NSTimer.scheduledTimerWithTimeInterval in Swift Playground
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.我在 Swift 中使用“NSTimer.scheduledTimerWithTimeInterval”看到的所有示例都使用“target: self”参数显示,但不幸的是,这不能直接在 Swift Playgrounds 中使用。
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()
You really should not be using NSTimer
these days.这些天你真的不应该使用
NSTimer
。 It's consumes a lot of resources, causes unnecessary battery drain, and the API lends itself to ugly code.它消耗大量资源,导致不必要的电池消耗,并且 API 会导致代码丑陋。
Use dispatch_after()
instead:使用
dispatch_after()
代替:
dispatch_after(0, dispatch_get_main_queue()) { () -> Void in
for counter in 0...1000 {
var b = counter
}
}
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.当然,由于计时器将在操场执行后触发,因此您需要等效于
timer.fire()
来强制代码立即执行,而不是在 0 秒延迟后执行。 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()
To get this to run directly within a Swift Playground, you need to embed the printFrom1To1000 function within a class and then set an instance of that class to the "target:" parameter instead of using "self".要使其直接在 Swift Playground 中运行,您需要在类中嵌入 printFrom1To1000 函数,然后将该类的实例设置为“target:”参数,而不是使用“self”。
Here's a full working example:这是一个完整的工作示例:
class myClass: NSTimer{
func printFrom1To1000() {
for counter in 0...1000 {
var b = counter
}
}
}
let myClassInstance = myClass()
var timer = NSTimer.scheduledTimerWithTimeInterval(0,
target: myClassInstance,
selector: Selector("printFrom1To1000"),
userInfo: nil,
repeats: false
)
timer.fire()
If you already have an object you are referencing (ie, updating a label), you can extend that type and use that function as the Selector.如果您已经有一个正在引用的对象(即更新标签),您可以扩展该类型并将该函数用作选择器。 I find this easier than creating a whole new class and instantiating a new object from it.
我发现这比创建一个全新的类并从中实例化一个新对象更容易。
extension SKLabelNode {
func updateMe() {
count++
label.text = "\(count)"
}
}
var timer = NSTimer.scheduledTimerWithTimeInterval(0.25,
target: label,
selector: Selector("updateMe"),
userInfo: nil,
repeats: true)
timer.fire()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.