在 Objective-C 中,Java 的“instanceof”关键字等价于什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/536396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Objective-C, what is the equivalent of Java's "instanceof" keyword?
提问by Dimitris
I would like to check whether an object (e.g. someObject) is assignable (cast-able) to a variable of another type (e.g. SpecifiedType). In Java, I can write:
我想检查一个对象(例如someObject)是否可分配(可转换)到另一种类型的变量(例如SpecifiedType)。在Java中,我可以写:
someObject instanceof SpecifiedType
A related question is finding whether the runtime type of an object is equal to a another type. In Java, I can write:
一个相关的问题是查找对象的运行时类型是否等于另一种类型。在Java中,我可以写:
someObject.getClass().equals(SpecifiedType.class)
How can this be done in Objective-C?
如何在 Objective-C 中做到这一点?
回答by mouviciel
Try [myObject class]for returning the class of an object.
尝试[myObject class]返回对象的类。
You can make exact comparisons with:
您可以与以下内容进行精确比较:
if ([myObject class] == [MyClass class])
but not by using directly MyClassidentifier.
但不是直接使用MyClass标识符。
Similarily, you can find if the object is of a subclass of your class with:
同样,您可以使用以下命令查找对象是否属于您的类的子类:
if ([myObject isKindOfClass:[AnObject class]])
as suggested by Jon Skeet and zoul.
正如 Jon Skeet 和 zoul 所建议的那样。
回答by Jon Skeet
From Wikipedia:
来自维基百科:
In Objective-C, for example, both the generic
ObjectandNSObject(in Cocoa/OpenStep) provide the methodisMemberOfClass:which returnstrueif the argument to the method is an instance of the specified class. The methodisKindOfClass:analogously returns true if the argument inherits from the specified class.
例如,在 Objective-C 中,泛型
Object和NSObject(在 Cocoa/OpenStep 中)都提供了如果方法 的参数是指定类的实例则isMemberOfClass:返回true的方法。isKindOfClass:如果参数继承自指定的类,则该方法类似地返回 true。
isKindOfClass:would be closest to instanceof, by the sounds of it.
isKindOfClass:instanceof从它的声音来看,将最接近。
回答by zoul
See the isKindOfClass:method in the NSObjectdocumentation. (The usual word of warning for such question is that checking the object class is often a sign of doing something wrong.)
请参阅NSObject文档中的isKindOfClass:方法。(对于此类问题,通常的警告词是检查对象类通常是做错事的标志。)

