Search code examples
iosswiftunrecognized-selector

unrecognized selector sent to instance in ViewController using Notifications


I've been looking around for a fix, but couldn't seem to fix it by myself.

I'm trying to sent notifications through my controller - model. I'm getting an error on my appdelegate saying:

[Test.ViewController naamInModelChangedHandler]: unrecognized selector sent to instance 0x7f81c85006c0

I'm sending my notification in my viewDidLoad like this:

        NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "naamInModelChangedHandler",
        name: "NAAM_CHANGED",
        object: model)

In my ViewController I made a function like this:

    func naamInModelChangedHandler ( notification:NSNotification ) {
    println("De naam in de model is veranderd naar \(model.naam!)")
            NSNotificationCenter.defaultCenter().removeObserver(
                self,
                name: "NAAM_CHANGED",
                object: model)
}

And this is how my model looks like (but I don't think this has anything to do with it? :

var naam: String? {
didSet {
    NSNotificationCenter.defaultCenter().postNotificationName("NAAM_CHANGED", object: self)
}

Anyone who could help me out fixing this error?


Solution

  • The name of the selector should be "naamInModelChangedHandler:". Note the : since naamInModelChangedHandler takes an NSNotification as an argument. Therefore, you should add the observer like so:

    NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector: "naamInModelChangedHandler:",
            name: "NAAM_CHANGED",
            object: model)