添加 C++ 时遇到问题对象到 Objective C 集合 (NSSet)
我正忙着在我的项目中使用 QRCodeReader 实现 ZXing。 QRCodeReader 主要是 C++ 和我的项目 Objective-C。 我已经成功地正确实现了它,因此我可以将 QRCodeReader 对象使用到我的 Objective-C 实现(.mm 文件)中。 但现在我需要将此 C++ 对象传递给 zxWidController.reader 属性。
这意味着我必须将 C++ 对象设置为 NSSet 对象。
QRCodeReader* qrcodeReader = new QRCodeReader();
NSSet *readers = [[NSSet alloc ] init];
[readers setByAddingObject:(id)qrcodeReader];
widController.readers = readers;
[readers release];
上面的代码就达到了目的。我将 C++ 对象转换为 (id),现在它可以正确编译。但这是正确的方法吗?
这种编程方式是执行此操作的正确方法吗?
还有其他/更好的方法来实现我的目标吗?
I'm busy implementing ZXing with a QRCodeReader into my project.
QRCodeReader is mainly C++ and my project objective-C.
I have managed to implement it properly so I can use the QRCodeReader objects into my objective-C implementation (.mm file).
But now I need to pass this C++ object to the zxWidController.reader property.
This means I will have to set the C++ object into an NSSet Object.
QRCodeReader* qrcodeReader = new QRCodeReader();
NSSet *readers = [[NSSet alloc ] init];
[readers setByAddingObject:(id)qrcodeReader];
widController.readers = readers;
[readers release];
The code above does the trick. I casted the C++ object to (id) and now it compiles properly. But is this the proper way to do it?
Is this manner of programming the proper way to do this?
Are there any other / better ways to achieve my goal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++ 类型不是 Objective C 类型。你不能向它发送消息,特别是保留和释放,而 NSSet 却可以。您想要使用一个同名的 Objective C 类型。 (我会更新我的其他答案)。
A C++ type is not an Objective C type. You cannot send it messages, in particular retain and release, which NSSet does. There's an Objective C type of the same name that you want to use. (I'll update my other answer).
不。您不能通过将任意指针强制转换为 id 来使其成为有效的 Objective-C 对象指针。
再说一次,不。
您可以尝试以下任意操作:
重新定义 zxWidController 类以获取指向 C++ 对象而不是 Obj-C 对象的指针。
将 qrcodeReader 包装在 NSValue 中。
看看 NSPointerArray 作为 NSSet 的替代品。在尝试使用它之前一定要阅读文档——您必须配置它的内存管理策略,以便为您存储的指针类型做正确的事情。
小问题:暂时忘记 qrcodeReader 指向 C++ 对象这一事实,创建一个空集以便可以向其中添加对象似乎很愚蠢。如果您打算使用 Obj-C 集,则可以使用 +setWithObject: 创建它,或者使用 NSMutableSet 代替。
No. You can't just make an arbitrary pointer into a valid Objective-C object pointer by casting it to id.
Again, no.
You can try any of the following:
Redefine your zxWidController class to take a pointer to a C++ object instead of an Obj-C object.
Wrap qrcodeReader in a NSValue.
Take a look at NSPointerArray as a replacement for NSSet. Definitely read the docs before you try to use it -- you have to configure it's memory management policies to do the right thing for the type of pointer you're storing.
Minor nitpick: Forgetting for a moment about the fact that qrcodeReader points to a C++ object, it seems silly to create an empty set just so that you can add an object to it. If you were going to use an Obj-C set, then either create it using +setWithObject: or use NSMutableSet instead.