【问题标题】:How to invoke a Swift method with parameters from Obj-C如何使用来自 Obj-C 的参数调用 Swift 方法
【发布时间】:2016-09-29 01:49:14
【问题描述】:

如果我有这样的 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)];

所以问题是如何将其推断为包含参数?

【问题讨论】:

    标签: ios objective-c swift


    【解决方案1】:

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

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

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

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

    [theObj methodWithParamWithMessage:@"message"];
    

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

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

    那么你可以这样做:

    [theObj methodWithParam:@"message"];
    

    【讨论】:

    • 值得注意的是,您可以使用 @objc(...) 属性覆盖 Objective-C 名称。
    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 2017-08-15
    • 1970-01-01
    • 2020-08-27
    • 2023-03-23
    相关资源
    最近更新 更多