Swift Nsnotificationcenter发布通知错误

时间:2015-01-22 12:35:31

标签: ios swift nsnotificationcenter unrecognized-selector nsnotification

发布通知功能有问题。

FirstViewController viewDidLoad我有这句话:

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

之后我有了这个功能:

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

TableViewController方法中didDeselectRowAtIndexPath类型的第二个视图控制器中,我有以下代码:

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

我收到此错误:

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

如果在ponresultado中的FirstViewController函数中,我会退出notification:NSNotification这样的参数:

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

我没有错误。为什么呢?

2 个答案:

答案 0 :(得分:7)

您需要在选择器名称后添加:

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

声明您的方法,例如它接受NSNotification对象:

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

答案 1 :(得分:0)

如果您的方法将NSNotification作为参数,则应在注册时将“:”添加到选择器。所以你的行:

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

变为

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