Protocol SomeProtocol {
func registerForPresetLoadedNotification()
}
extension SomeProtocol {
func registerForPresetLoadedNotification() {
NSNotificationCenter.defaultCenter().addObserver(self as AnyObject,
selector: #selector(presetLoaded(_:)),
name: kPresetLoadedNotificationName,
object: nil)
}
func presetLoaded(notification: NSNotification) {
}
}
Swift 中, 如上定义一个协议, 协议中有一个方法, 通过扩展实现协议方法
registerForPresetLoadedNotification, 在该方法中又调用
presetLoaded方法, 此时会报错 Argument of '#selector' refers to a method that is not exposed to Objective-C, 提示需要在方法前添加 @objc, 添加后又报错 @objc can only be used with members of classes, @objc protocols, and concrete extensions of classes,提示让删除@objc.
Stack Overflow 上的链接: https://stackoverflow.com/questions/38980887/protocol-extension-on-an-objc-protocol
因为 Swift protocol Extension 中的方法对 OC 不可见, 所以不能使用 selector 方法, 解决方法可以使用block 方法, 或参考:
https://www.jessesquires.com/blog/avoiding-objc-in-swift/