如何使用Obj-C中的参数调用Swift方法

时间:2016-09-28 17:04:19

标签: ios objective-c swift

如果我有这样的Obj-C方法:

- (void) methodWithParam: (NSString*) message
{}

然后我可以用这样的参数调用它:

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

但是,如果methodWithParam是swift类的方法(或扩展名),例如:

extension UIApplication
{
    func methodWithParam(message: String)
    {}

然后,当通过相同的Objective-C代码调用时,会出现无法识别的选择器异常。

  

[UIApplication methodWithParam:]:发送到无法识别的选择器   实例

但是,如果该方法没有参数:

extension UIApplication
{
    func methodWithoutParam()
    {}

然后可以从Obj-C代码中成功调用它,如下所示:

[theObj performSelector:@selector(methodWithoutParam)];

所以问题是如何推断这个参数?

1 个答案:

答案 0 :(得分:3)

从Swift方法名称到Objective-C方法名称的转换过程包括遵循Cocoa约定的Swift方法的参数名称(即添加“With”)。

因此,此方法的Objective-C中的名称为methodWithParamWithMessage:,因此performSelector:行将如下所示:

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

请注意,您也可以直接执行此操作:

[theObj methodWithParamWithMessage:@"message"];

正如MartinR指出的那样,如果您愿意,还可以明确指定翻译的名称:

@objc(methodWithParam:)
func methodWithParam(message: String)
{
    //...

然后你可以这样做:

[theObj methodWithParam:@"message"];