C++ 对象作为 Objective-C++ 属性

C++ object as an Objective-C++ property

我想在我的 Objective-C class 中声明一个 C++ 属性。

我应该设置什么样的属性? strongretain 似乎会导致错误说它不是对象。

如何正确管理它的内存?

IIRC,你需要像管理任何其他 C++ 对象一样管理它,所以只需使用 assign 作为属性,你应该很好。

你是对的,属性不能是weakstrongretained;为此,它必须是指向 Objective-C object 的指针。如果您不在 C++ 属性 上使用任何属性,它将默认为 unsafe_unretained,assign,atomic

假设 Objective-C(++) object 控制 C++ 的生命周期 属性:

  • 因为在 Objective-C 中用 C++ object 做不了太多事情,
    属性 在 Objective-C++ 代码中最有用,你可以在其中混合
    Objective-C 和 C++。
  • 因为你必须自己管理属性的内存,你 需要自定义 setter.
  • 因为属性默认为atomic,你需要使用 setter 中的同步,也需要自定义 getter。你 可以声明它 nonatomic,在这种情况下你不需要 同步并且不需要自定义 getter.
  • 您可以实现 dealloc 以确保在以下情况下释放 C++ object Objective-C++ object 消失了。

这里有一些来自 Apple 的有用文档:https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html

这是一个简单的例子。假设您为 属性 使用的 C++ class 称为 MyCPP。在 header 你可以有:

@interface ClassOCPP : NSObject

// This property can only be used in Objective-C++ code
#ifdef __cplusplus
@property /*(unsafe_unretained,assign,atomic)*/ MyCPP * myCPP;
#endif

// Other stuff may be usable in regular Objective-C code.

@end

实现如下(在 .mm 文件中;记住,它是 Objective-C++):

@implementation ClassOCPP
{
    MyCPP * _myCPP;
}
-(id)init {
    self = [super init];
    _myCPP = NULL;
    return self;
}

-(void)setMyCPP:(MyCPP*)newVal {
    @synchronized(self) {
        delete _myCPP;  // it's OK to delete a NULL pointer
        _myCPP = newVal;
    }
}

-(MyCPP*)myCPP {
    return _myCPP;
}

-(void)dealloc {
    puts("De-allocating ClassOCPP.");
    delete _myCPP;
}

@end