I have an Objective-C protocol which is used by mostly objective-C objects and one or two Swift objects.
I would like to extend the protocol in Swift and add 2 functions. One to register for a notification and another to handle the notification.
If I add these
func registerForPresetLoadedNotification() {
NSNotificationCenter.defaultCenter().addObserver(self as AnyObject,
selector: #selector(presetLoaded(_:)),
name: kPresetLoadedNotificationName,
object: nil)
}
func presetLoaded(notification: NSNotification) {
}
I get an error on the #selector which says Argument of '#selector' refers to a method that is not exposed to Objective-C
If I then mark presetLoaded as @objc
I get an error which says @objc can only be used with members of classes, @objc protocols, and concrete extensions of classes
I also cannot mark the protocol extension as @objc
When I create the Objective-C protocol as a Swift protocol I get the same error.
Is there a way to achieve this that will work for Objective-C and Swift classes that use the protocol?
Indeed, you can't really mark a function of a protocol extension as @objc (or dynamic, which is equivalent by the way). Only methods of a class are allowed to be dispatched by Objective-C runtime.
In your particular case, if you really want to make it through protocol extension, I can propose the following solution (assuming your original protocol is named ObjcProtocol).
Let's make a wrapper for our notification handler:
Now we need extend our ObjcProtocol to introduce required logic
I know this might look not so elegant, so I'd really consider changing a core approach.
One note: You do might want to restrict your protocol extension
I found a way to do it :) Just avoid @objc all together :D
Example