In Swift 3, to register a notification, I can do the following ways:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.n1(notification:)), name: Notification.Name("123"), object: nil)
func n1(notification: Notification){
print("123")
}
// #selector is more brief
NotificationCenter.default.addObserver(self, selector: #selector(n2), name: Notification.Name("456"), object: nil)
func n2(notification: Notification){
print("456")
}
However, in Xcode 9.0 beta 2 (Swift 4.0), when I register a notification this way, the object method should have a prefix @objc
, why? What is the best practice to use Notification?
Argument of '#selector' refers to instance method 'n1(notification:)' that is not exposed to Objective-C
//Add '@objc' to expose this instance method to Objective-C
@objc func n1(notification: Notification){
print("123")
}
@objc func n2(notification: Notification){
print("456")
}