Ios – NSNotification unrecognized selector sent to instance in Swift

iosswift

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?

Best Answer

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")
}
Related Topic