nyitguy nyitguy - 5 months ago 31
Swift Question

Swift nstimer accessing function other class

Having trouble running the function in a different class as a selector for NStimer.

class VariClass
{
func updateUILoop()
{
print("updating UI")
}
}


In the app delegate I have

let values = VariClass()


In the appdelegate I have.

let timer = NSTimer(fireDate: NSDate(), interval: 5, target: self, selector: #selector(values.updateUILoop), userInfo: nil, repeats: true)


The function works perfectly if I run it manually.

getvalues.updateUILoop()

Answer

You want NSTimer to invoke func updateUILoop on the values object, so the target for timer's callback should be values, not self:

let timer = NSTimer(fireDate: NSDate(), interval: 5, target: self.values, selector: #selector(VariClass.updateUILoop), userInfo: nil, repeats: true)
Comments