WatchKit "unrecognized selector sent to instance" when trying to fire an NSTimer object in Swift

259 views Asked by At

In my WatchKit extensions InterfaceController.swift file I call a function, from within the awakeWithContext function, that runs an animated sequence of images.

I have used an NSTimer object to time a delay and then fire off a second animated sequence.

var nsTimerObject:NSTimer = NSTimer.scheduledTimerWithTimeInterval(showCodeDelay, target: self, selector: "showCode(counterCode1)", userInfo: nil, repeats: false);

After the first animation runs I get an error preventing the second animation being fired by the function specified in the selector:

[Code_Break_WatchKit_Extension.InterfaceController showCode(counterCode1)]: unrecognized selector sent to instance 0x60800014c3f0

I have the iOS Device App and the WatchKit extension ticked in the Target Membership

I found this thread on stackoverflow which sent me down this route.

Another thread seemed to suggest I may need to do something around "Sharing" but it was unclear.

It feels like it should be simple but I'm stumped.

I am new to this so please be gentle on me :)

1

There are 1 answers

0
Headstock67 On BEST ANSWER

Sorted it!

The problem was in the syntax for setting the selector function and passing the parameters required for the function to work.

I changed:

var nsTimerObject:NSTimer = NSTimer.scheduledTimerWithTimeInterval(showCodeDelay, target: self, selector: "showCode(counterCode1)", userInfo: nil, repeats: false);

to:

var nsTimerObject:NSTimer = NSTimer.scheduledTimerWithTimeInterval(showCodeDelay, target: self, selector: "showCode:", userInfo: counterCode1, repeats: false);

Then I had to alter my showCodeDelay function declaration from:

func showCodeDelay(counterCode: Int){

//code........
}

to:

func showCodeDelay(nsTimerObject:NSTimer){
        var tempCounterCode = nsTimerObject.userInfo as! NSNumber
        var counterCode = Int(tempCounterCode)

        //code........
}

I'm just getting my head around it I wrongly first thought that I was simply pointing the selector at the function I had created with its required parameters.

However it looks like when taking this approach the function being referred to in the selector has to receive the actual NSTimer object and from this extract the parameters required from the userInfo

Once I'd figured this out the next problem I had was extracted the value I had passed in userInfo because Xcode wanted me treat it as an AnyObject! that can't be expressed as an Int so I extracted userInfo from the nsTimerObject object as an NSNumber and then downcast this to an Int

There may be a simpler more elegant way to achieve the downcast but at least this worked.