【发布时间】:2017-06-30 02:09:54
【问题描述】:
在 Swift 3 中,要注册通知,我可以通过以下方式:
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")
}
但是,在 Xcode 9.0 beta 2 (Swift 4.0) 中,当我以这种方式注册通知时,对象方法应该有一个前缀 @objc,为什么?使用通知的最佳做法是什么?
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")
}
【问题讨论】: