Reputation: 2035
What is the object life cycle of a C++ object in an Objective-C class, and how do you keep it in memory?
I tried opaque structure, create instance, but that always leads to null.
Upvotes: 4
Views: 2637
Reputation: 100668
If your C++ object is going to have the same life-cycle as the Objective-C object which contains it, you can simply place the C++ object (not a pointer to it) in the Objective-C class:
@interface MyClass {
CppObject myObject;
}
@end
Upvotes: 1
Reputation: 163268
You can own a C++ object in your Objective-C class by creating a new
instance of your C++ class inside of your init
method, assigning it to an ivar, then in -dealloc
, call delete
on the ivar:
@interface SomeClass : NSObject {
SomeCPPClass *cpp_object;
}
@end
@implementation SomeClass
- (id) init {
self = [super init];
if(self) {
cpp_object = new SomeCPPClass();
}
return self;
}
- (void) dealloc {
delete cpp_object;
[super dealloc];
}
@end
Upvotes: 6