如何将 Objective-C++ 对象添加到 NSMutableDictionary?
How to add Objective-C++ object to a NSMutableDictionary?
我正在使用 metaio
SDK 在 iOS 中创建增强现实应用程序。在我的应用程序中,我有一个如下所示的对象,
metaio::IGeometry* geometryModel = m_metaioSDK->createGeometry([modelFile UTF8String]);
我尝试将其添加到 NSMutableDictionary
、
[_currentObjectDirectory setObject:geometryModel forKey:@"1"];
currentObjectDirectory
是我的 NSMutableDictionary
对象。有什么可行的方法吗?
提前致谢!
您不能将 C++ 对象添加到 Cocoa 容器中。
您可以使用 C++ 容器,或者必须将 C++ 对象包装到 Objective-C 对象中。
编辑:这里是关于 Objective-C++ 的链接(我没有检查它们。)
http://philjordan.eu/article/strategies-for-using-c++-in-objective-c-projects
http://www.drdobbs.com/cpp/interoperating-between-c-and-objective-c/240165502
以前,Apple 有相关文档:
什么 is correct. However, you could probably use a NSValue
object with valueWithPointer:
包装你的 C++ 指针。
NSValue *geometryModelWrapper = [NSValue valueWithPointer:(void *)geometryModel];
[_currentObjectDirectory setObject:geometryModelWrapper forKey:@"1"];
要取回值,请使用 pointerValue
:
metaio::IGeometry* geometryModel = [_currentObjectDirectory[@"1"] pointerValue];
同样,正如阿明所说,你必须小心内存管理。 NSValue
不会内存管理您的指针,并且您必须确保在 NSValue
包装器仍然存在时它不会被释放。
Read the doc carefully.
This question 非常接近你想要达到的目标。
我正在使用 metaio
SDK 在 iOS 中创建增强现实应用程序。在我的应用程序中,我有一个如下所示的对象,
metaio::IGeometry* geometryModel = m_metaioSDK->createGeometry([modelFile UTF8String]);
我尝试将其添加到 NSMutableDictionary
、
[_currentObjectDirectory setObject:geometryModel forKey:@"1"];
currentObjectDirectory
是我的 NSMutableDictionary
对象。有什么可行的方法吗?
提前致谢!
您不能将 C++ 对象添加到 Cocoa 容器中。
您可以使用 C++ 容器,或者必须将 C++ 对象包装到 Objective-C 对象中。
编辑:这里是关于 Objective-C++ 的链接(我没有检查它们。)
http://philjordan.eu/article/strategies-for-using-c++-in-objective-c-projects http://www.drdobbs.com/cpp/interoperating-between-c-and-objective-c/240165502
以前,Apple 有相关文档:
什么 NSValue
object with valueWithPointer:
包装你的 C++ 指针。
NSValue *geometryModelWrapper = [NSValue valueWithPointer:(void *)geometryModel];
[_currentObjectDirectory setObject:geometryModelWrapper forKey:@"1"];
要取回值,请使用 pointerValue
:
metaio::IGeometry* geometryModel = [_currentObjectDirectory[@"1"] pointerValue];
同样,正如阿明所说,你必须小心内存管理。 NSValue
不会内存管理您的指针,并且您必须确保在 NSValue
包装器仍然存在时它不会被释放。
Read the doc carefully.
This question 非常接近你想要达到的目标。