ver*_*rec 3 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
Run Code Online (Sandbox Code Playgroud)
这是在ARC下完成它们时删除C++ land对象的正确方法吗?
这样可行,但您可以考虑采用其他几种方法来避免NSValue:
创建一个ObjC包装器,管理单个实例SomeCppClass(并删除其中的一个对象dealloc).这可以使它们在许多情况下更容易处理(自动转换std::string到NSString访问器等).这基本上NSValue是为您做的,但通过创建自己的自定义类,您可以获得更大的灵活性.这通常是我的首选方法.
将C++对象存储在C++容器中vector,然后你只需删除vector它就可以了.您可以用来shared_ptr将不可复制的对象放入vector.如果你不想要STL的开销,这是可以理解的shared_ptr,但它们在Cocoa中很容易获得.
| 归档时间: |
|
| 查看次数: |
1273 次 |
| 最近记录: |