簡體   English   中英

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

[英]ARC/ObjC++: C++ object inside an ObjC container

考慮:

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對象的正確方法嗎?

這可行,但您可以考慮采用其他幾種方法來避免NSValue

  • 創建管理的單一實例的ObjC包裝SomeCppClass (並在其刪除只是一個對象dealloc )。 這可以使它們在許多情況下更容易處理(在訪問器中自動將std::string轉換為NSString等)這基本上是NSValue為你做的,但你通過創建自己的自定義可以獲得更大的靈活性類。 這通常是我的首選方法。

  • 將C ++對象存儲在C ++容器(如vector ,然后您只需要刪除該vector ,它就更容易解決問題。 您可以使用shared_ptr將不可復制的對象放入vector 如果你不想要STL和shared_ptr的開銷,這是可以理解的,但它們在Cocoa中很容易獲得。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM