本文介绍了在代码中实现 NSTimer - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在代码中使用/实现 NSTimer 时遇到了一些麻烦.到目前为止,我有这个:
I am having a bit of trouble using / implementing NSTimer into code. So far, i have this:
//Delay function from http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861
func delay(delay:Double, closure:()->()) {
dispatch_after(
//adds block for execution at a specific time
dispatch_time(
//creates a dispatch time relative to default clock
DISPATCH_TIME_NOW,
//Indicates that something needs to happen imediately
Int64(delay * Double(NSEC_PER_SEC))
//a 64bit decleration that holds the delay time times by the amount of nanoseconds in one seconds, inorder to turn the 'delay' input into seconds format
),
dispatch_get_main_queue(), closure)
}
@IBAction func computerTurn(){
if(isFirstLevel){levelLabel.text = ("Level 1"); isFirstLevel = false}
else{ level++ }
var gameOrderCopy = gameOrder
var randomNumber = Int(arc4random_uniform(4))
gameOrder.append(randomNumber)
var i = 0
var delayTime = Double(1)
println(Double(NSEC_PER_SEC))
for number in self.gameOrder{
if number == 0{
delay(delayTime++){self.greenButton.highlighted = true}
self.delay(delayTime++){
self.greenButton.highlighted = false
}
}
else if number == 1{
delay(delayTime++){self.redButton.highlighted = true}
self.delay(delayTime++){
self.redButton.highlighted = false
}
}
else if number == 2{
delay(delayTime++){self.yellowButton.highlighted = true}
self.delay(delayTime++){
self.yellowButton.highlighted = false
}
}
else if number == 3{
delay(delayTime++){self.blueButton.highlighted = true}
self.delay(delayTime++){
self.blueButton.highlighted = false
}
}
println(delayTime)
}
}
我需要做的是替换定时器功能,或者去掉它,并与这里发生的事情一样,但使用 NSTimer.
What i need to do, is replace the timer function, or get rid of it, and do the same as whats happening here, but using NSTimer.
谢谢
推荐答案
NSTimer
在这种情况下可能有点笨拙,因为它需要使用 target-action 或 NSInvocation
.但是,NSTimer
与 CFRunLoopTimer
是免费桥接的,您可以使用块调用:
NSTimer
can be a little clunky in this context because it requires using either target-action or NSInvocation
. However, NSTimer
is toll-free bridged with CFRunLoopTimer
, which you can call with a block:
func delay(delay:Double, closure:()->()) {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0) { _ in
closure()
}
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
}
这篇关于在代码中实现 NSTimer - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!