Essence of chickens Essence of chickens - 1 year ago 102
Swift Question

How to invoke a Swift method with parameters from Obj-C

If I have an Obj-C method like this:

- (void) methodWithParam: (NSString*) message

Then I can invoke it with an argument like this:

[theObj performSelector:@selector(methodWithParam:) withObject:@"message"];

However if methodWithParam is an method (or extension) of a swift class such as this:

extension UIApplication
func methodWithParam(message: String)

Then there is an unrecognized selector exception when invoked via the same Objective-C code.

[UIApplication methodWithParam:]: unrecognized selector sent to

But, if the method does not have a parameter:

extension UIApplication
func methodWithoutParam()

Then it can sucessfully be invoked from the Obj-C code like this:

[theObj performSelector:@selector(methodWithoutParam)];

So the question is how can this be extrapolated to include a parameter?

Answer Source

The translation process from Swift method name to Objective-C method name includes the Swift method's parameter name, following Cocoa conventions (i.e., adding "With").

The name in Objective-C of this method is therefore methodWithParamWithMessage:, so the performSelector: line would look like this:

[theObj performSelector:@selector(methodWithParamWithMessage:) withObject:@"message"];

Note that you can also just do this directly:

[theObj methodWithParamWithMessage:@"message"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download