Created
June 16, 2018 12:43
-
-
Save rikusouda/ef38c19e08cf167fe22ea661cd63d3a8 to your computer and use it in GitHub Desktop.
In ARC, C++ std::vector has Objective-C instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Debug out of Xcode 9.4