How to correctly pass selector as parameter in swift How to correctly pass selector as parameter in swift swift swift

How to correctly pass selector as parameter in swift


Here's the big clue in your console output:

-[Slider.GKSessionControllerH gestureDownHandler]: unrecognized selector sent to instance 0x7f912857a420

So, the problem is that rather than attempting to call gestureDownHandler on your ViewController, GKSessionControllerH is registering itself to be the receiver of the notification.

We need to pass in both the selector and the object to call the selector on.

func registerNotification(gesture: GKGesture, gestureHandler: AnyObject, selector: Selector) {    let notificationName = "ReceiveGesture\(gesture.rawValue)"    NSNotificationCenter.defaultCenter().addObserver(gestureHandler, selector: gestureHandler, name: notificationName, object: nil)}

And now, to register:

sessionCtrl.registerNotification(.Up, gestureHandler: self, selector: "gestureUpHandler")

Alternatively, and arguably more Swift-like, we can take a more closure-based approach.

First, let's make GKSessionControllerH receive the notifications, and we'll pass it a closure, which it'll keep track of to call when the notification is received.

In GKSessionControllerH,

var gestureActions = [()->Void] // an array of void-void closuresfunc gestureHandler() {    for action in gestureActions {        action()    }}func registerNotification(gesture: GKGesture, action:()->Void) {    let notificationName = "ReceiveGesture\(gesture.rawValue)"    NSNotificationCenter.defaultCenter().addObserver(self, selector: "gestureHandler", name: notificationName, object: nil)}

And now, we pass in a closure (which can be a method):

In ViewController:

func registerNotification() {    sessionCtrl.registerNotification(.Up, action: gestureUpHandler)}

Now obviously, this will need a little more logic to handle all your different gesture types, but the gist of it is here.