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

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

问题描述:

考虑:

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 ++陆地对象时,这是正确的方法吗?

Is this the correct approach to delete C++ land objects when you're done with them under ARC?

这是可行的,但是您可以考虑采用其他两种方法来避免NSValue:

This will work, but you may consider a couple of other approaches to avoid the NSValue:

  • 创建一个ObjC包装器,该包装器管理SomeCppClass的单个实例(并仅删除其dealloc中的那个对象).这可以使它们在很多情况下都更容易处理(在访问器中自动将std::string转换为NSString等).这基本上是NSValue为您执行的操作,但是通过创建,您将获得更大的灵活性您自己的自定义类.通常这是我的首选方法.

  • Create an ObjC wrapper that manages a single instance of SomeCppClass (and deletes just that one object in its dealloc). This can make them a bit easier to deal with in many cases (automatically converting std::string to NSString in the accessors, etc.) This is basically what NSValue is doing for you, but you get much more flexibility by creating your own custom class. This is usually my preferred approach.

将C ++对象存储在C ++容器(例如vector)中,然后只需要删除vector,就可以更轻松地提取内容.您可以使用shared_ptr将不可复制的对象放入vector.不需要STL和shared_ptr的开销是可以理解的,但是它们在Cocoa中很容易获得.

Store the C++ objects in a C++ container such as vector and then you just have to delete the vector and it's easier to pull things out. You can used shared_ptr to put non-copyable objects into a vector. It is understandable if you don't want the overhead of STL and shared_ptr, but they are readily available in Cocoa.