Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotificationCenter addObserver in Swift while call a private method

Tags:

ios

swift

I use the addObserver API to receive notification:

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

and my method is :

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

yes,it works! but while I change method methodOFReceivedNotication to private:

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

xCode send me an error: unrecognized selector sent to instance

how to call a private method while the target is self? I doesn't want to expose methodOFReceivedNotication method to any other.

like image 680
SubCycle Avatar asked Oct 21 '14 09:10

SubCycle


2 Answers

Just mark it with the dynamic modifier or use the @objc attribute in your method declaration

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

or

@objc private func methodOFReceivedNotication(notification: NSNotification){
    //Action take on Notification
}
like image 114
ylin0x81 Avatar answered Sep 18 '22 09:09

ylin0x81


Have you considered using -addObserverForName:object:queue:usingBlock:?

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

or instead of calling the private method, just performing the action.

NSNotificationCenter.defaultCenter().addObserverForName("NotificationIdentifier", object: nil, queue: nil, usingBlock: {
    [unowned self] note in
    // Action take on Notification
})
like image 43
Jeffery Thomas Avatar answered Sep 22 '22 09:09

Jeffery Thomas