2

I have an SKScene that makes itself an observer of a notification named " showPhotoForMoodNotification" with an associated selector called : "eventListenerDidReceiveNotification:" .

The eventListenerDidReceiveNotification is declared as a function that can throw and exception as follows:

func eventListenerDidReceiveNotification(notif:NSNotification) throws { }

But I noticed that when the notification is received by the SKScene, the compiler doesn't associate the signature of this "eventListenerDidReceiveNotification" method with the signature of the "selector" in the addObserver called, which looks like thisL

NSNotificationCenter.defaultCenter().addObserver(self, selector: "eventListenerDidReceiveNotification:", name: "showPhotoForMoodNotification", object: nil)

The error i get is this: enter image description here

So, my guess is that the "throws" part of the method's signature is not compatible with the "selector" part of the nsnotification "addObserver" call, because if I eliminate the "throws" part from the "eventListenerDidReceiveNotification" method declaration, things work.

So do I have to add anything more to the addObserver "selector" part to describe this method as a method that throws an exception?

thanks

malena
  • 798
  • 11
  • 26

2 Answers2

0

Possible answer here. BTW, in Swift 2.2 (actually, i don't know what version you are using) there is new syntax for selectors which is recommended way to use it. (IBAction connected to button TouchUpInside event in storyboard)

Actually, i just tested this code and it worked:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(test(_:)), name: "TestNotification", object: nil)
}

@objc private func test(notification: NSNotification) throws {
    print("notification")
}

@IBAction private func fireNotification() {
    NSNotificationCenter.defaultCenter().postNotificationName("TestNotification", object: nil)
}
Community
  • 1
  • 1
Maksym Musiienko
  • 1,248
  • 8
  • 16
0

IIRC, Swift methods like

func f(x: T) throws -> U

Are viewed in Objective C as

- (nullable U *)fWithX:(T *)x error:(NSError **)errorPtr;

So you may try adding that error: part in your selector.

EDIT:

And

func f() throws -> U

Becomes

- (nullable U *)fAndReturnError:(NSError **)errorPtr;
user28434'mstep
  • 6,290
  • 2
  • 20
  • 35