2

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()
Wyetro
  • 8,439
  • 9
  • 46
  • 64
nyitguy
  • 598
  • 4
  • 18

1 Answers1

3

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)
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I get this error. "Argument of '#selector' refers to a method that is not exposed to Objective-C". – nyitguy Jun 30 '16 at 00:09
  • 1
    @nyitguy [Use `@objc` on the function from which you make a selector](http://stackoverflow.com/q/36818083/335858) – Sergey Kalinichenko Jun 30 '16 at 00:11
  • 1
    @nyitguy I am not sure about the reason behind the `@objc` marker. My only guess is that selectors are kept in Swift only for Objective-C interoperability. In all other situations they are replaced by closures. Hence, Swift language designers wanted programmers to mark functions eligible for selector constructions with a special tag, to make the intention explicit. – Sergey Kalinichenko Jun 30 '16 at 00:33