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

Sub*_*cle 12 ios swift

我使用addObserverAPI来接收通知:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)    
Run Code Online (Sandbox Code Playgroud)

我的方法是:

func methodOFReceivedNotication(notification: NSNotification){
//Action take on Notification
}    
Run Code Online (Sandbox Code Playgroud)

是的,它有效!但是当我将方法更改methodOFReceivedNotication为私有时:

private func methodOFReceivedNotication(notification: NSNotification){
//Action take on Notification
}    
Run Code Online (Sandbox Code Playgroud)

xCode发给我一个错误: unrecognized selector sent to instance

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

yli*_*x81 14

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

dynamic private func methodOFReceivedNotication(notification: NSNotification){
    //Action take on Notification
}
Run Code Online (Sandbox Code Playgroud)

要么

@objc private func methodOFReceivedNotication(notification: NSNotification){
    //Action take on Notification
}
Run Code Online (Sandbox Code Playgroud)

  • @StevenMarlowe,这篇文章([link](http://blog.untitledkingdom.co.uk/obj-c-vs-swift/))可能会有所帮助. (2认同)

Jef*_*mas 10

你考虑过用过-addObserverForName:object:queue:usingBlock:吗?

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

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

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