cocoa touch -- 测试对象是否是 Objective-C 对象
假设我有一个对象。可能是 Objective-C 对象;可能是一个 C++ 对象。有没有办法测试哪个不会抛出任何异常?
编辑:我很高兴使用任何有效的构造,包括模板(如果它们能完成这项工作)。
Suppose I have an object. Might be an objective-C object; might be a C++ object. Is there a way to test which it is that won't throw any exceptions?
EDIT: I'm happy to use any construct that works, including templates if they will do the job.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一位朋友在 Cocoa with Love 上发现了这个博客。显然,这个问题并不小。
A friend found this on the Cocoa with Love blog. Apparently, the problem is not trivial.
由于您可以使用模板,因此您可以创建某种类型的函数,该函数采用通用模板参数,然后使用您在 C++ 中使用的所有类和宏来实例化您的基类。如果它不是 C++ 类,则该函数返回 false。举例来说:
我在这里专门使用指针而不是引用,因为据我所知,您可以使用指向 Objective-C 对象的指针实例化 C++ 模板,而使用 Objective-C 对象本身进行实例化是行不通的。如果这个假设不正确,那么您可以通过从指针更改为引用来让生活变得更轻松一些。
Since you can use templates, you could do something where you create some type of function that takes a generic template argument, and then instantiate your base-class with all the classes you're using from C++ with a macro. If it's not a C++ class, then the function returns false. So for instance:
I'm specifically using pointers here rather than references because it's my understanding that you can instantiate a C++ template with a pointer to an Objective-C object, where-as instantiations with Objective-C objects themselves doesn't work. If this assumption is not correct, then you can make life a little easier by changing from pointers to references.
我认为如果类型是静态可用的(正如使用模板作为选项所暗示的那样),它可以变得简单得多。 Objective-C 对象将隐式转换为 NSObject 和/或“id” - C++ 对象不会(每个类至少没有自定义代码来添加强制转换运算符)。
这里的函数原型通过 const& 传递参数,因为我在使用 Objective-C 消息返回的 Objective-C 类型进行模板化时遇到了问题,而这似乎在普通 NSObject* 不起作用的情况下有效。
I think it can be made a lot simpler than that if the type is available statically (as implied by using a template being an option). Objective-C objects will be implicitly convertible to NSObject and/or 'id' - C++ objects will not (without at least custom code per class to add the cast operator).
The function prototypes here pass the parameter by
const&
because I've had issues with templating with Objective-C types as returned by Objective-C messages, and this seems to work where plain NSObject* doesn't.