考虑:
class SomeCppClass {
public:
SomeCppClass() {} ;
~SomeCppClass() {} ;
} ;
@interface Test1 : NSObject
- (id) init ;
@property (strong, nonatomic) NSMutableArray * container ;
@end
@implementation Test1
@synthesize container ;
- (id) init {
if (self = [super init]) {
container = [NSMutableArray arrayWithCapacity:10] ;
[container addObject:[NSValue valueWithPointer:new SomeCppClass()]] ;
}
return self ;
}
- (void) dealloc {
for (NSValue * v in container) {
SomeCppClass * c = (SomeCppClass *) [v pointerValue] ;
delete c ;
}
}
@end
这是在 ARC 下删除 C++ 陆地对象的正确方法吗?
最佳答案
这会起作用,但您可以考虑一些其他方法来避免 NSValue
:
创建一个 ObjC 包装器来管理
SomeCppClass
的单个实例(并仅删除其dealloc
中的那个对象)。这可以使它们在许多情况下更容易处理(在访问器中自动将std::string
转换为NSString
等)这基本上就是NSValue
是为你做的,但你可以通过创建自己的自定义类来获得更大的灵 active 。这通常是我的首选方法。将 C++ 对象存储在诸如
vector
之类的 C++ 容器中,然后您只需删除vector
就可以更轻松地提取内容。您可以使用shared_ptr
将不可复制的对象放入vector
中。如果您不想要 STL 和shared_ptr
的开销,这是可以理解的,但它们在 Cocoa 中很容易获得。
关于c++ - 弧/ObjC++ : C++ object inside an ObjC container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8897495/