NSNotificationCenter addObserver在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方法暴露给其他人。

只需用dynamic修饰符标记它,或者在方法声明中使用@objc属性即可

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

要么

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

你有没有考虑使用-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 }) 

NSNotificationCenter.defaultCenter()。addObserver(self,selector:“methodOFReceivedNotication:”,name:“NotificationIdentifier”,object:nil)

在iOS9中,您可以使用:

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