如何在同一框架内访问 Objective-C 中的内部 Swift 类? [英] How to access an internal Swift class in Objective-C within the same framework?

查看:20
本文介绍了如何在同一框架内访问 Objective-C 中的内部 Swift 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用混合框架.在 Obj-C 文件中导入,但内部类不可见,只有公共类.

Working on a mixed framework. imported inside the Obj-C file but the internal classes are not visible, only the public ones.

文档明确指出 Swift 和 Obj-C 之间应该可以使用内部类:

The documentation clearly states the internal clasees should be available between Swift and Obj-C:

将 Swift 导入到 Objective-C
要将一组 Swift 文件导入到与 Objective-C 代码相同的框架目标中,您不需要需要将任何内容导入框架的伞头文件中.相反,为您的 Swift 代码导入 Xcode 生成的头文件到任何你想从中使用 Swift 代码的 Objective-C .m 文件中.因为为框架目标生成的标头是框架的公共接口,只有标有公共的声明修饰符出现在为框架目标生成的标头中.你仍然可以使用标有来自框架的 Objective-C 部分的内部修饰符,只要它们是在继承自Objective-C 类.有关访问级别修饰符的更多信息,请参阅访问控制Swift 编程语言 (Swift 2).

代码示例(使用框架创建新项目)

Code Sample (Create a new project with a framework)

// SwiftObject.swift

public class SwiftObject: NSObject {
    public class func doSomething() {}
}

internal class YetAnotherSwiftObject: NSObject {
    internal class func doSomething() {}
}

<小时>

// SomeObject.m file

@implementation SomeObject

- (void)someMethod {
    [SwiftObject doSomething];
}

- (void)someOtherMethod {
    [YetAnotherSwiftObject doSomething]; // Use of undeclared identifier
}

@end

推荐答案

如文档中所示,标有 internal 修饰符的声明不会出现在生成的标头中,因此编译器不知道关于他们,因此投诉.当然,您可以使用 performSelector 方法发送消息,但这不方便且容易出错.我们只需要帮助编译器知道那些声明就在那里.

As indicated in the docs, declarations marked with internal modifier don't appear in the generated header, so the compiler does not know about them and thus complaints. Of course, you could send messages using performSelector approach, but that's not convenient and bug-prone. We just need to help the compiler know that those declarations are there.

首先,我们需要使用 @objc 属性变体,它允许您在 Objective-C 中为符号指定名称:

First, we need to use @objc attribute variant that allows you to specify name for your symbol in Objective-C:

// SwiftObject.swift

@objc(SWIFTYetAnotherSwiftObject)
internal class YetAnotherSwiftObject: NSObject {
    internal class func doSomething() {}
}

然后您只需要使用要在代码中使用的方法创建 @interface 声明 - 这样编译器会很高兴,并且还应用 SWIFT_CLASS 宏使用您之前指定的符号名称 - 所以链接器会选择实际的实现:

And then you just need to create @interface declaration with the methods you want to use in your code - so the compiler will be happy, and also apply SWIFT_CLASS macro with the symbol name you've specified earlier - so the linker would pick the actual implementation:

// SomeObject.m file

SWIFT_CLASS("SWIFTYetAnotherSwiftObject")
@interface YetAnotherSwiftObject : NSObject

+ (void)doSomething;

@end


@implementation SomeObject

- (void)someOtherMethod {
    [YetAnotherSwiftObject doSomething]; // Should work now !!!
}

@end

  • 为了清楚起见,我在 .m 文件中使用了接口声明,更好的选择是将此类声明合并到 .h 文件中,并包含它.
  • 通过在该接口中声明方法,我们向编译器做出了承诺,如果你将一个不存在的方法(或签名错误等)放在那里,它不会抱怨.显然,你会在这种情况下会在运行时崩溃 - 所以要小心.
  • 这篇关于如何在同一框架内访问 Objective-C 中的内部 Swift 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆