0xSina
0xSina

Reputation: 21553

Cannot invoke scheduledTimer

I have this very simple code to trigger a timer:

var timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(2), target: self, selector: "timerDidFire:", userInfo: nil, repeats: true)

However it's giving me:

Cannot invoke 'scheduledTimerWithTimeInterval' with an argument list of type '(Double, target: TestVC -> () -> TestVC, selector: String, userInfo: nil, repeats: Bool)'

Which doesn't make any sense, my arguments types match exactly the required ones.

Here's the function definition:

scheduledTimerWithTimeInterval(ti: NSTimeInterval, target aTarget: AnyObject, selector aSelector: Selector, userInfo: AnyObject?, repeats yesOrNo: Bool) -> NSTimer

What am I doing wrong?

Upvotes: 0

Views: 732

Answers (3)

Marcos
Marcos

Reputation: 471

this is what works fine for me in Swift:

1) var updateTimer: NSTimer?

2) In viewDidLoad: updateTimer = NSTimer.scheduledTimerWithTimeInterval(Double(2), target: self, selector: Selector("updateB:"), userInfo: nil, repeats: true)

3) func updateB(timer:NSTimer!) { ... }

Hope it helps ...

Upvotes: 0

Martin R
Martin R

Reputation: 539735

When used in the initial value expression for a property

 class TestVC : UIViewController (

      var timer = ... some expression using `self` ...

      // ...
 }

self is not an instance of TestVC, but a "curried function" of the type

  TestVC -> () -> TestVC

and that's where the strange error message comes from. The instance itself is not fully initialized at this point. This is similar to the problem in ViewController.Type does not have a member named, and the same solution can be applied here:

Declare the variable as an optional (or implicitly unwrapped optional) and initialize it in some method, e.g. in viewDidLoad:

class TestVC: UIViewController {

    var timer : NSTimer?

    override func viewDidLoad() {
        super.viewDidLoad()
        timer = NSTimer.scheduledTimerWithTimeInterval( ... )
    }

    // ...
}

Upvotes: 4

Duncan C
Duncan C

Reputation: 131418

Swift's compiler errors are often really horrible. If they don't seem to make sense, it's probably because they don't.

When you get a compiler error that makes no sense, remember to translate it to "There's something wrong with this line. I have no idea what, so I'm going to make up something totally unrelated and report that."

Or just "Derp?"

My money is on your timerDidFire method. Post the function definition for that method.

Also, a class that receives NSTimer methods has to be an Objective-C class. Usually it's a UIViewController so you don't have to anything special since all view controllers inherit from NSObject.

Upvotes: 1

Related Questions