Home > database >  Swift Timer inside class not working as expected
Swift Timer inside class not working as expected

Time:05-20

I am having difficulty understanding why a Timer works outside of a class but not inside. I assume it has something to do with scope but can not find any resource that has help me understand the problem.

Here is my playground code:

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()

CodePudding user response:

The timer only exists as a local variable so once the starttimer function is done the timer disappears.

Add it as a property to the class to keep it around

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")
    }
}
  • Related