16

I've set up an observer as follows, which includes the logYes() function:

class SplashPageVC: UIViewController {

    func logYes() {
        println("Yes");
    }

    override func viewDidLoad() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "logYes:", name: "userValid", object: nil)
    }
}

I've wired the following IBAction to a button:

class LoginVC: UIViewController {
    @IBAction func loginSubmitted(sender : AnyObject) {
        NSNotificationCenter.defaultCenter().postNotificationName("userValid", object: nil)
    }
}

I am getting the following error when I tap the button:

[_TtC13Explorer12SplashPageVC self.logYes:]: unrecognized selector sent to instance 

I have tried a bunch of different selectors, with no luck:

logYes
logYes:
logYes()
logYes():

I'm out of ideas. Any insights? tyvm :)

References:
NSNotification not being sent when postNotificationName: called
NSNotificationCenter addObserver in Swift
Delegates in swift?

Forge
  • 6,538
  • 6
  • 44
  • 64
kmiklas
  • 13,085
  • 22
  • 67
  • 103

1 Answers1

39

I think your original selector (logYes:) is correct – it's your function that should be rewritten. Notification observer functions receive the posted notification as an argument, so you should write:

func logYes(note: NSNotification) {
    println("Yes")
}
Tim
  • 59,527
  • 19
  • 156
  • 165
  • 2
    Yes! I was barking up the wrong tree. I ♥ you man. Can't choose this as accepted answer for another 10 minutes. – kmiklas Jun 18 '14 at 21:18
  • 8
    By the way, one may get an unrecognized selector exception if declared logYes like "private func logYes(notification: NSNotification)" – Arthur Gevorkyan May 05 '15 at 11:45
  • @ArthurGevorkyan saved my day! but how can't the selector be private? isn't it only called in the class declares it? – bluenowhere Oct 29 '15 at 03:35
  • 3
    @sharky101, it is called by the sender (any UIControl) so in your selector should be accessible for the sender, not only the class that assigns the target for the action. Cheers and good luck :) – Arthur Gevorkyan Oct 29 '15 at 05:48