[英]ARC/ObjC++: C++ object inside an ObjC container
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? 这是在ARC下完成它们时删除C ++ land对象的正确方法吗?
This will work, but you may consider a couple of other approaches to avoid the NSValue
: 这可行,但您可以考虑采用其他几种方法来避免NSValue
:
Create an ObjC wrapper that manages a single instance of SomeCppClass
(and deletes just that one object in its dealloc
). 创建管理的单一实例的ObjC包装SomeCppClass
(并在其删除只是一个对象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. 这可以使它们在许多情况下更容易处理(在访问器中自动将std::string
转换为NSString
等)这基本上是NSValue
为你做的,但你通过创建自己的自定义可以获得更大的灵活性类。 This is usually my preferred approach. 这通常是我的首选方法。
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. 将C ++对象存储在C ++容器(如vector
,然后您只需要删除该vector
,它就更容易解决问题。 You can used shared_ptr
to put non-copyable objects into a vector
. 您可以使用shared_ptr
将不可复制的对象放入vector
。 It is understandable if you don't want the overhead of STL and shared_ptr
, but they are readily available in Cocoa. 如果你不想要STL和shared_ptr
的开销,这是可以理解的,但它们在Cocoa中很容易获得。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.