我需要混合使用 Objective-C 和 C++。我想将所有 C++ 内容隐藏在一个类中,而将所有其他内容保留为纯 Objective-C。问题是我想要一些 C++ 类作为实例变量。这意味着它们必须在头文件中提及,它被其他类包含并且 C++ 开始传播到整个应用程序。到目前为止,我能想到的最佳解决方案如下所示:
#ifdef __cplusplus
#import "cppheader.h"
#endif
@interface Foo : NSObject
{
id regularObjectiveCProperty;
#ifdef __cplusplus
CPPClass cppStuff;
#endif
}
@end
这行得通。实现文件有一个 mm
扩展名,所以它被编译为混合了 C++ 的 Objective-C,#ifdef
解锁了 C++ 的东西,然后我们就开始了。当其他一些纯 Objective-C 类导入 header 时,C++ 内容被隐藏,类看不到任何特殊之处。这看起来像 hack,有更好的解决方案吗?
最佳答案
这听起来像是接口(interface)/@protocol 的经典用法。为 API 定义一个 objective-c 协议(protocol),然后使用您的 Objective-C++ 类提供该协议(protocol)的实现。这样客户只需要知道协议(protocol)而不是实现的头。所以给定原始实现
@interface Foo : NSObject
{
id regularObjectiveCProperty;
CPPClass cppStuff;
}
@end
我会定义一个协议(protocol)
//Extending the NSObject protocol gives the NSObject
// protocol methods. If not all implementations are
// descended from NSObject, skip this.
@protocol IFoo <NSObject>
// Foo methods here
@end
并修改原来的Foo
声明
@interface Foo : NSObject <IFoo>
{
id regularObjectiveCProperty;
CPPClass cppStuff;
}
@end
然后客户端代码可以使用类型 id<IFoo>
并且不需要编译为 Objective-C++。显然你可以传递 Foo
的实例给这些客户。
关于C++ 类作为 Objective-C 类的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1056911/