gpt4 book ai didi

ios - 如何在同一框架内访问 Objective-C 中的内部 Swift 类?

转载 作者:IT王子 更新时间:2023-10-29 05:26:00 25 4
gpt4 key购买 nike

在混合框架上工作。在 Obj-C 文件中导入,但内部类不可见,只有公共(public)类。

文档清楚地说明了内部类在 Swift 和 Obj-C 之间应该可用:

Importing Swift into Objective-C
To import a set of Swift files in the same framework target as your Objective-C code, you don’t need to import anything into the umbrella header for the framework. Instead, import the Xcode-generated header file for your Swift code into any Objective-C .m file you want to use your Swift code from. Because the generated header for a framework target is part of the framework’s public interface, only declarations marked with the public modifier appear in the generated header for a framework target. You can still use Swift methods and properties that are marked with the internal modifier from within the Objective-C part of your framework, as long they are declared within a class that inherits from an Objective-C class. For more information on access-level modifiers, see Access Control in The Swift Programming Language (Swift 2).

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

// 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 修饰符标记的声明不会出现在生成的 header 中,因此编译器不知道它们,因此会投诉。当然,您可以使用 performSelector 方法发送消息,但这不方便且容易出错。我们只需要帮助编译器知道那些声明就在那里。

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

// SwiftObject.swift

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

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

// SomeObject.m file

SWIFT_CLASS("SWIFTYetAnotherSwiftObject")
@interface YetAnotherSwiftObject : NSObject

+ (void)doSomething;

@end


@implementation SomeObject

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

@end
  • 为了清楚起见,我在 .m 文件中使用了接口(interface)声明,更好的选择是将此类声明合并到 .h 文件中,并包含它。
  • 通过在该接口(interface)中声明方法,我们向编译器做出 promise ,如果您将不存在的方法(或签名错误等)放在那里,它不会提示。显然,您会在这种情况下会在运行时崩溃 - 所以要小心。

关于ios - 如何在同一框架内访问 Objective-C 中的内部 Swift 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com