SubCycle
SubCycle

Reputation: 481

NSNotificationCenter addObserver in Swift while call a private method

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.

Upvotes: 12

Views: 6870

Answers (2)

linimin
linimin

Reputation: 6377

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
}

Upvotes: 14

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

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
})

Upvotes: 10

Related Questions