gpt4 book ai didi

swift - 在代码中实现 NSTimer - Swift

转载 作者:搜寻专家 更新时间:2023-11-01 06:47:07 25 4
gpt4 key购买 nike

我在代码中使用/实现 NSTimer 时遇到了一些麻烦。到目前为止,我有这个:

//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。

谢谢

最佳答案

NSTimer 在此上下文中可能有点笨拙,因为它需要使用目标操作或 NSInvocation。但是,NSTimer 是免费桥接 CFRunLoopTimer 的,您可以使用 block 调用它:

func delay(delay:Double, closure:()->()) {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0) { _ in
closure()
}
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
}

关于swift - 在代码中实现 NSTimer - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29337610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com