Search code examples
iosswiftnsnotificationcenterunrecognized-selectornsnotification

Swift Nsnotificationcenter post notification error


I have a problem with post notification function.

In the FirstViewController in viewDidLoad I have this sentence:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "ponresultado", name: "resultadobusqueda", object: nil)

After that I have the function:

func ponresultado(notification:NSNotification)
{
    var oDato : oDatoSel = notification.object as oDatoSel
}

In second view controller of type TableViewController in didDeselectRowAtIndexPath method I have this code:

var oDato : oDatoSel = oDatoSel()
oDato.id = "1"
oDato.nombre = "test"
NSNotificationCenter.defaultCenter().postNotificationName("resultadobusqueda", object: oDato)

I receive this error:

[App.FirstViewController ponresultado]: unrecognized selector sent to instance 0x797d2310

If in my ponresultado function in FirstViewController, I quit notification:NSNotification parameter like this:

func ponresultado()
{
    var oDato : oDatoSel = notification.object as oDatoSel
}

I don't have the error. Why?


Solution

  • You need to add a : after the selector's name:

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "ponresultado:", name: "resultadobusqueda", object: nil)
    

    As your method is declared such as it accepts a NSNotification object:

    func ponresultado(notification:NSNotification)
    {
        var oDato : oDatoSel = notification.object as oDatoSel
    }