Consider:
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
Is this the correct approach to delete C++ land objects when you're done with them under ARC?
This will work, but you may consider a couple of other approaches to avoid the
NSValue
:Create an ObjC wrapper that manages a single instance of
SomeCppClass
(and deletes just that one object in itsdealloc
). This can make them a bit easier to deal with in many cases (automatically convertingstd::string
toNSString
in the accessors, etc.) This is basically whatNSValue
is doing for you, but you get much more flexibility by creating your own custom class. This is usually my preferred approach.Store the C++ objects in a C++ container such as
vector
and then you just have to delete thevector
and it's easier to pull things out. You can usedshared_ptr
to put non-copyable objects into avector
. It is understandable if you don't want the overhead of STL andshared_ptr
, but they are readily available in Cocoa.