ARC / ObjC ++:ObjC容器中的C ++对象

时间:2012-01-17 15:44:59

标签: c++ objective-c automatic-ref-counting

考虑:

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 ++ land对象的正确方法吗?

1 个答案:

答案 0 :(得分:5)

这样可行,但您可以考虑采用其他几种方法来避免NSValue

  • 创建一个ObjC包装器,用于管理SomeCppClass的单个实例(并删除其dealloc中的一个对象)。这可以使它们在许多情况下更容易处理(在访问器中自动将std::string转换为NSString等等。)这基本上就是NSValue正在为你做的事情,但是你通过创建自己的自定义类来获得更大的灵活性。这通常是我的首选方法。

  • 将C ++对象存储在诸如vector的C ++容器中,然后您只需要删除vector,就可以更轻松地解决问题。您可以使用shared_ptr将不可复制的对象放入vector。如果你不想要STL和shared_ptr的开销,这是可以理解的,但它们在Cocoa中很容易获得。

相关问题