我很難理解為什么計時器在課堂外作業而不是在課堂內作業。我認為它與范圍有關,但找不到任何有助于我理解問題的資源。
這是我的游樂場代碼:
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()
uj5u.com熱心網友回復:
計時器僅作為區域變數存在,因此一旦starttimer函式完成,計時器就會消失。
將其作為屬性添加到類中以保留它
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")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/478789.html
上一篇:在C 中將通用類分配為null
