我在Swift中的Operation的子类中设置了此代码。但我无法弄清楚为什么计时器只调用选择器一次。
class DogOperationRun : DogOperation {
let thisDog:Dog?
let operationID:Int?
var runDistance:Double?
var dogSpeed:Double?
var runTimeLeft:Double = 0.0
var currentRunDistance:Double = 0.0
private var interval = 0.0
private var cycle = 0.0
private var dogTimer:Timer?
init(thisDog:Dog, operationID:Int, runDistance:Double, dogSpeed:Double) {
self.thisDog = thisDog
self.operationID = operationID
self.runDistance = runDistance
self.dogSpeed = dogSpeed
super.init(self.operationID!)
}
override func main() {
guard isCancelled == false else {
operationIsFinished = true
return
}
startRun()
}
func startRun() {
operationIsExecuting = true
if let distance = runDistance, let thisDogSpeed = dogSpeed {
runTimeLeft = distance
interval = distance/thisDogSpeed
dogTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(runDog), userInfo: nil, repeats: true)
}
}
@objc func runDog() {
runTimeLeft -= interval
cycle += 1
if runTimeLeft > 0 {
runDistance = interval * cycle
print("\(self.thisDog!.name) has run \(runDistance!) meters!")
} else {
dogTimer?.invalidate()
operationIsFinished = true
}
}
}
和超类
import Foundation
class DogOperation: Operation {
public var id:Int
//going to over ride the existing variable and return my private one
override var isExecuting: Bool {
return operationIsExecuting
}
var operationIsExecuting = false {
didSet {
willChangeValue(forKey: "isExecuting")
print("Operation \(id) will execute")
didChangeValue(forKey: "isExecuting")
print("Operation \(id) is executing")
}
}
override var isFinished: Bool {
return operationIsFinished
}
var operationIsFinished = false {
didSet {
willChangeValue(forKey: "isFinished")
print("Operation \(id) will finish")
didChangeValue(forKey: "isFinished")
print("Operation \(id) is finished")
}
}
init(_ id:Int) {
self.id = id
}
}
这样称呼它:
let lodiDogRun = DogOperationRun(thisDog: aDog, operationID: 1, runDistance: 100.0, dogSpeed: 12.0)
let pretzelDogRun = DogOperationRun(thisDog: nextDog, operationID: 2, runDistance: 100.0, dogSpeed: 14.0)
myOperationQueue.addOperations([lodiDogRun, pretzelDogRun], waitUntilFinished: true)
编辑Matt:dogRun被调用的唯一时间是我用dogTimer.fire()强制计时器。对于我捕获它的实例,它正在线程5上运行: