NSNotificationCenter在Swift中添加addObserver,同时调用私有方法

时间:2014-10-21 09:15:57

标签: ios swift

我使用addObserver API接收通知:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)    

我的方法是:

func methodOFReceivedNotication(notification: NSNotification){
//Action take on Notification
}    
是的,它有效! 但是我将方法methodOFReceivedNotication更改为私有:

private func methodOFReceivedNotication(notification: NSNotification){
//Action take on Notification
}    

xCode向我发送错误:unrecognized selector sent to instance

如何在目标为self时调用私有方法?我不想将methodOFReceivedNotication方法暴露给任何其他方法。

2 个答案:

答案 0 :(得分:14)

只需使用dynamic修饰符进行标记,或在方法声明中使用@objc属性

dynamic private func methodOFReceivedNotication(notification: NSNotification){
    //Action take on Notification
}

@objc private func methodOFReceivedNotication(notification: NSNotification){
    //Action take on Notification
}

答案 1 :(得分:10)

您是否考虑过使用-addObserverForName:object:queue:usingBlock:

NSNotificationCenter.defaultCenter().addObserverForName("NotificationIdentifier", object: nil, queue: nil, usingBlock: {
    [unowned self] note in
    self.methodOFReceivedNotication(note)
})

或者不是调用私有方法,只是执行操作。

NSNotificationCenter.defaultCenter().addObserverForName("NotificationIdentifier", object: nil, queue: nil, usingBlock: {
    [unowned self] note in
    // Action take on Notification
})