Skip to content

Instantly share code, notes, and snippets.

@rikusouda
Created June 16, 2018 12:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rikusouda/ef38c19e08cf167fe22ea661cd63d3a8 to your computer and use it in GitHub Desktop.
Save rikusouda/ef38c19e08cf167fe22ea661cd63d3a8 to your computer and use it in GitHub Desktop.
In ARC, C++ std::vector has Objective-C instances
#import <Foundation/Foundation.h>
#include <string>
#include <vector>
@interface ObjcClass: NSObject
@property (nonatomic, readonly) NSString *name;
- (instancetype)initWithName:(NSString *)name;
- (void)speak;
@end
@implementation ObjcClass
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (self) {
_name = name;
}
return self;
}
- (void)dealloc { NSLog(@"%@ is deleted", self.name); }
- (void)speak { NSLog(@"I am %@", self.name); }
@end
class CppClass {
public:
std::vector<ObjcClass*> m_objcInstances; // ### Is ARC enabled? ###
public:
CppClass()
: m_objcInstances() {
for (int i = 0; i < 5; ++i) {
auto name = [NSString stringWithFormat:@"Objc instance %d", i];
m_objcInstances.push_back([[ObjcClass alloc] initWithName:name]);
}
}
~CppClass() { NSLog(@"CppClass is deleted"); }
void Speak() const {
for (auto objc : m_objcInstances) {
[objc speak];
}
}
};
int main(int argc, const char * argv[]) {
ObjcClass *reference = nil;
@autoreleasepool {
NSLog(@"Hello, World!");
const auto cppClass = CppClass();
cppClass.Speak();
reference = cppClass.m_objcInstances[2]; // retain
}
NSLog(@"End");
return 0;
}
@rikusouda
Copy link
Author

Debug out of Xcode 9.4

2018-06-16 21:41:57.900903+0900 objective_cpp_practice[6036:398272] Hello, World!
2018-06-16 21:41:57.901257+0900 objective_cpp_practice[6036:398272] I am Objc instance 0
2018-06-16 21:41:57.901283+0900 objective_cpp_practice[6036:398272] I am Objc instance 1
2018-06-16 21:41:57.901301+0900 objective_cpp_practice[6036:398272] I am Objc instance 2
2018-06-16 21:41:57.901317+0900 objective_cpp_practice[6036:398272] I am Objc instance 3
2018-06-16 21:41:57.901338+0900 objective_cpp_practice[6036:398272] I am Objc instance 4
2018-06-16 21:41:57.901354+0900 objective_cpp_practice[6036:398272] CppClass is deleted
2018-06-16 21:41:57.901372+0900 objective_cpp_practice[6036:398272] Objc instance 4 is deleted
2018-06-16 21:41:57.901414+0900 objective_cpp_practice[6036:398272] Objc instance 3 is deleted
2018-06-16 21:41:57.901555+0900 objective_cpp_practice[6036:398272] Objc instance 1 is deleted
2018-06-16 21:41:57.901594+0900 objective_cpp_practice[6036:398272] Objc instance 0 is deleted
2018-06-16 21:41:57.901624+0900 objective_cpp_practice[6036:398272] End
2018-06-16 21:41:57.901648+0900 objective_cpp_practice[6036:398272] Objc instance 2 is deleted

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment