在Objective-C中,什么是等同于Java的“instanceof”关键词? [英] In Objective-C, what is the equivalent of Java's "instanceof" keyword?
问题描述
我想检查一个对象(例如 someObject
)是否可分配给另一个类型的变量(例如 SpecifiedType
)。在Java中,我可以写:
someObject instanceof SpecifiedType
一个相关的问题是查找对象的运行时类型是否等于另一个类型。在Java中,我可以写:
someObject.getClass()。equals(SpecifiedType.class)
$如何在Objective-C中做到这一点?解决方案尝试 [myObject class]
返回对象的类。
与以下内容进行精确比较:
if([myObject class] == [MyClass class])
,但不能直接使用 MyClass
标识符。
类似地,你可以找到对象是你的类的子类的: if由Jon Skeet和zoul建议的[myObject isKindOfClass:[AnObject class]])
>
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 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:
someObject.getClass().equals(SpecifiedType.class)
How can this be done in Objective-C?
解决方案 Try [myObject class]
for returning the class of an object.
You can make exact comparisons with:
if ([myObject class] == [MyClass class])
but not by using directly MyClass
identifier.
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.
这篇关于在Objective-C中,什么是等同于Java的“instanceof”关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!