合使用Objective-C,C++和Objective-C++
- #include <string>
- class CppObject
- {
- public:
- void ExampleMethod(const std::string& str);
- // constructor, destructor, other members, etc.
- };
#include <string>
class CppObject
{
public:
void ExampleMethod(const std::string& str);
// constructor, destructor, other members, etc.
};
- #import <Foundation/Foundation.h>
- #import "CppObject.h"
- @interface ObjcObject : NSObject {
- CppObject wrapped;
- }
- - (void)exampleMethodWithString:(NSString*)str;
- // other wrapped methods and properties
- @end
#import <Foundation/Foundation.h>
#import "CppObject.h"
@interface ObjcObject : NSObject {
CppObject wrapped;
}
- (void)exampleMethodWithString:(NSString*)str;
// other wrapped methods and properties
@end
然后在ObjcObject.mm中实现这些方法。不过,此时会在两个头文件(ObjcObject.h&CppObject.h)中得到一个预处理和编译错误。问题出在#include和#import上。对于预处理器而言,它只做文本的替换操作。所以#include和#import本质上就是递归地复制和粘贴引用文件的内容。这个例子中,使用#import "ObjcObject.h"等价于插入如下代码:
- // [首先是大量Foundation/Foundation.h中的代码]
- // [无法包含<string>],因为它仅存在于C++模式的include path中
- class CppObject
- {
- public:
- void ExampleMethod(const std::string& str);
- // constructor, destructor, other members, etc.
- };
- @interface ObjcObject : NSObject {
- CppObject wrapped;
- }
- - (void)exampleMethodWithString:(NSString*)str;
- // other wrapped methods and properties
- @end
// [首先是大量Foundation/Foundation.h中的代码]
// [无法包含<string>],因为它仅存在于C++模式的include path中
class CppObject
{
public:
void ExampleMethod(const std::string& str);
// constructor, destructor, other members, etc.
};
@interface ObjcObject : NSObject {
CppObject wrapped;
}
- (void)exampleMethodWithString:(NSString*)str;
// other wrapped methods and properties
@end
- #import "ObjcObject.h"
- @interface ObjcObject () // note the empty parentheses
- - (void)methodWeDontWantInTheHeaderFile;
- @end
- @implementation ObjcObject
- // etc.
#import "ObjcObject.h"
@interface ObjcObject () // note the empty parentheses
- (void)methodWeDontWantInTheHeaderFile;
@end
@implementation ObjcObject
// etc.
GCC也支持这个操作。不过clang还支持添加ivar块,也就是你还可以声明C++类型的实例变量,既可以在class extension中,也可以在@implementation开始的位置。本例中的ObjcObject.h可以被精简为:
- #import <Foundation/Foundation.h>
- @interface ObjcObject : NSObject
- - (void)exampleMethodWithString:(NSString*)str;
- // other wrapped methods and properties
- @end
#import <Foundation/Foundation.h>
@interface ObjcObject : NSObject
- (void)exampleMethodWithString:(NSString*)str;
// other wrapped methods and properties
@end
去掉的部分都移到实现文件的class extension中 (ObjcObject.mm):
- #import "ObjcObject.h"
- #import "CppObject.h"
- @interface ObjcObject () {
- CppObject wrapped;
- }
- @end
- @implementation ObjcObject
- - (void)exampleMethodWithString:(NSString*)str
- {
- // NOTE: str为nil会建立一个空字串,而不是引用一个指向UTF8String空指针.
- std::string cpp_str([str UTF8String], [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
- wrapped.ExampleMethod(cpp_str);
- }
#import "ObjcObject.h"
#import "CppObject.h"
@interface ObjcObject () {
CppObject wrapped;
}
@end
@implementation ObjcObject
- (void)exampleMethodWithString:(NSString*)str
{
// NOTE: str为nil会建立一个空字串,而不是引用一个指向UTF8String空指针.
std::string cpp_str([str UTF8String], [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
wrapped.ExampleMethod(cpp_str);
}
如果我们不需要interface extension来声明额外的属性和方法,ivar块仍然可以放在@implementation开始位置:
- #import "ObjcObject.h"
- #import "CppObject.h"
- @implementation ObjcObject {
- CppObject wrapped;
- }
- - (void)exampleMethodWithString:(NSString*)str
- {
- // NOTE: str为nil会建立一个空字串,而不是引用一个指向UTF8String空指针.
- std::string cpp_str([str UTF8String], [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
- wrapped.ExampleMethod(cpp_str);
- }
#import "ObjcObject.h"
#import "CppObject.h"
@implementation ObjcObject {
CppObject wrapped;
}
- (void)exampleMethodWithString:(NSString*)str
{
// NOTE: str为nil会建立一个空字串,而不是引用一个指向UTF8String空指针.
std::string cpp_str([str UTF8String], [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
wrapped.ExampleMethod(cpp_str);
}
- @interface ObjcObject () {
- CppObject* wrapped; // 指针!会在alloc时初始为NULL.
- }
- @end
- @implementation ObjcObject
- - (id)initWithSize:(int)size
- {
- self = [super init];
- if (self)
- {
- wrapped = new CppObject(size);
- if (!wrapped) self = nil;
- }
- return self;
- }
- //...
@interface ObjcObject () {
CppObject* wrapped; // 指针!会在alloc时初始为NULL.
}
@end
@implementation ObjcObject
- (id)initWithSize:(int)size
{
self = [super init];
if (self)
{
wrapped = new CppObject(size);
if (!wrapped) self = nil;
}
return self;
}
//...
如果是使用C++异常, 也可以使用 try {...} catch {...}把创建过程封装起来. 相应地,还要显式地释放封闭对象:
- - (void)dealloc
- {
- delete wrapped;
- [super dealloc]; // 如果使用了ARC,这句就要略去
- }
- (void)dealloc
{
delete wrapped;
[super dealloc]; // 如果使用了ARC,这句就要略去
}
作者接着提到了另一个方法,显示分配一块内存,然后在它的基础上调用new来创建对象。首先声明char wrapped_mem[sizeof(CppObject)]; 再使用wrapped = new(wrapped_mem) CppObject();创建了实例wrapped。释放时if (wrapped) wrapped->~CppObject(); 这样虽然可行,但不建议使用。
- #import <Foundation/Foundation.h>
- @interface ABCWidget
- - (void)init;
- - (void)reticulate;
- // etc.
- @end
#import <Foundation/Foundation.h>
@interface ABCWidget
- (void)init;
- (void)reticulate;
// etc.
@end
这样的类定义在Objective-C++中是没有问题的,但在纯C++的代码是不允许的:
- #import "ABCWidget.h"
- namespace abc
- {
- class Widget
- {
- ABCWidget* wrapped;
- public:
- Widget();
- ~Widget();
- void Reticulate();
- };
- }
#import "ABCWidget.h"
namespace abc
{
class Widget
{
ABCWidget* wrapped;
public:
Widget();
~Widget();
void Reticulate();
};
}
一个纯粹的C++编译器在Foundation.h中的代码和ABCWidget声明位置出错。
- namespace abc
- {
- struct WidgetImpl;
- class Widget
- {
- WidgetImpl* impl;
- public:
- Widget();
- ~Widget();
- void Reticulate();
- };
- }
namespace abc
{
struct WidgetImpl;
class Widget
{
WidgetImpl* impl;
public:
Widget();
~Widget();
void Reticulate();
};
}
然后在Widget.mm中:
- #include "Widget.hpp"
- #import "ABCWidget.h"
- namespace abc
- {
- struct WidgetImpl
- {
- ABCWidget* wrapped;
- };
- Widget::Widget() :
- impl(new WidgetImpl)
- {
- impl->wrapped = [[ABCWidget alloc] init];
- }
- Widget::~Widget()
- {
- if (impl)
- [impl->wrapped release];
- delete impl;
- }
- void Widget::Reticulate()
- {
- [impl->wrapped reticulate];
- }
- }
#include "Widget.hpp"
#import "ABCWidget.h"
namespace abc
{
struct WidgetImpl
{
ABCWidget* wrapped;
};
Widget::Widget() :
impl(new WidgetImpl)
{
impl->wrapped = [[ABCWidget alloc] init];
}
Widget::~Widget()
{
if (impl)
[impl->wrapped release];
delete impl;
}
void Widget::Reticulate()
{
[impl->wrapped reticulate];
}
}
- #include <objc/objc-runtime.h>
- namespace abc
- {
- class Widget
- {
- id /* ABCWidget* */ wrapped;
- public:
- Widget();
- ~Widget();
- void Reticulate();
- };
- }
#include <objc/objc-runtime.h>
namespace abc
{
class Widget
{
id /* ABCWidget* */ wrapped;
public:
Widget();
~Widget();
void Reticulate();
};
}
不建议向id对象直接发送消息。这样你会失去很多编译器的检查机制,特别是对于不同类中有着相同selector名字的不同方法时。所以:
- #include "Widget.hpp"
- #import "ABCWidget.h"
- namespace abc
- {
- Widget::Widget() :
- wrapped([[ABCWidget alloc] init])
- {
- }
- Widget::~Widget()
- {
- [(ABCWidget*)impl release];
- }
- void Widget::Reticulate()
- {
- [(ABCWidget*)impl reticulate];
- }
- }
#include "Widget.hpp"
#import "ABCWidget.h"
namespace abc
{
Widget::Widget() :
wrapped([[ABCWidget alloc] init])
{
}
Widget::~Widget()
{
[(ABCWidget*)impl release];
}
void Widget::Reticulate()
{
[(ABCWidget*)impl reticulate];
}
}
像这样的类型转换很容易在代码中隐藏错误,再尝试一个更好的方式。在头文件中:
- #ifdef __OBJC__
- @class ABCWidget;
- #else
- typedef struct objc_object ABCWidget;
- #endif
- namespace abc
- {
- class Widget
- {
- ABCWidget* wrapped;
- public:
- Widget();
- ~Widget();
- void Reticulate();
- };
- }
#ifdef __OBJC__
@class ABCWidget;
#else
typedef struct objc_object ABCWidget;
#endif
namespace abc
{
class Widget
{
ABCWidget* wrapped;
public:
Widget();
~Widget();
void Reticulate();
};
}
如果这个头文件被一个mm文件引用,编译器可以充分识别到正确的类。 如果是在纯C++模式中引用,ABCWidget*是一个等价的id类型:定义为typedef struct objc_object* id; 。 #ifdef块还可以被进一步放到一个可重用的宏中:
- #ifdef __OBJC__
- #define OBJC_CLASS(name) @class name
- #else
- #define OBJC_CLASS(name) typedef struct objc_object name
- #endif
#ifdef __OBJC__
#define OBJC_CLASS(name) @class name
#else
#define OBJC_CLASS(name) typedef struct objc_object name
#endif