Swift class 内的计时器未按预期工作
Swift Timer inside class not working as expected
我很难理解为什么 Timer 在 class 之外工作,但在内部却不行。我认为它与范围有关,但找不到任何有助于我理解问题的资源。
这是我的游乐场代码:
import UIKit
import Dispatch
// Timer inside a class
print ("\nStarting Class based Timer Section\n")
class mytest {
init () {
print ("mytest Classs init()")
}
func starttimer(){
print ("mytest Classs starttimer()")
let timer = DispatchSource.makeTimerSource()
timer.setEventHandler() {
self.doIt()
print ("y")
}
timer.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(1))
timer.activate()
}
func doIt() {
let wherefrom = "Inside"
print( "\(wherefrom) of Class")
}
}
var tst = mytest()
tst.starttimer()
// Stand alone timer works outside of a class
print ("\nStarting Stand alone Timer Section\n")
func doIt(){
let wherefrom = "Outside"
print( "\(wherefrom) of Class")
}
let timer = DispatchSource.makeTimerSource()
timer.setEventHandler() {
doIt()
print ("x")
}
timer.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(1))
timer.activate()
计时器仅作为局部变量存在,因此一旦 starttimer
函数完成,计时器就会消失。
将它作为 属性 添加到 class 以保留它
class mytest {
var timer: DispatchSourceTimer?
init () {
print ("mytest Classs init()")
}
func starttimer(){
print ("mytest Classs starttimer()")
timer = DispatchSource.makeTimerSource()
timer?.setEventHandler() {
self.doIt()
print ("y")
}
timer?.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(1))
timer?.activate()
}
func doIt() {
let wherefrom = "Inside"
print( "\(wherefrom) of Class")
}
}
我很难理解为什么 Timer 在 class 之外工作,但在内部却不行。我认为它与范围有关,但找不到任何有助于我理解问题的资源。
这是我的游乐场代码:
import UIKit
import Dispatch
// Timer inside a class
print ("\nStarting Class based Timer Section\n")
class mytest {
init () {
print ("mytest Classs init()")
}
func starttimer(){
print ("mytest Classs starttimer()")
let timer = DispatchSource.makeTimerSource()
timer.setEventHandler() {
self.doIt()
print ("y")
}
timer.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(1))
timer.activate()
}
func doIt() {
let wherefrom = "Inside"
print( "\(wherefrom) of Class")
}
}
var tst = mytest()
tst.starttimer()
// Stand alone timer works outside of a class
print ("\nStarting Stand alone Timer Section\n")
func doIt(){
let wherefrom = "Outside"
print( "\(wherefrom) of Class")
}
let timer = DispatchSource.makeTimerSource()
timer.setEventHandler() {
doIt()
print ("x")
}
timer.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(1))
timer.activate()
计时器仅作为局部变量存在,因此一旦 starttimer
函数完成,计时器就会消失。
将它作为 属性 添加到 class 以保留它
class mytest {
var timer: DispatchSourceTimer?
init () {
print ("mytest Classs init()")
}
func starttimer(){
print ("mytest Classs starttimer()")
timer = DispatchSource.makeTimerSource()
timer?.setEventHandler() {
self.doIt()
print ("y")
}
timer?.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(1))
timer?.activate()
}
func doIt() {
let wherefrom = "Inside"
print( "\(wherefrom) of Class")
}
}