In Objective-C, what is the equivalent of Java'

2019-01-20 23:38发布

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?

3条回答
倾城 Initia
2楼-- · 2019-01-20 23:59

From Wikipedia:

In Objective-C, for example, both the generic Object and NSObject (in Cocoa/OpenStep) provide the method isMemberOfClass: which returns true if the argument to the method is an instance of the specified class. The method isKindOfClass: analogously returns true if the argument inherits from the specified class.

isKindOfClass: would be closest to instanceof, by the sounds of it.

查看更多
Ridiculous、
3楼-- · 2019-01-21 00:08

See the isKindOfClass: method in the NSObject documentation. (The usual word of warning for such question is that checking the object class is often a sign of doing something wrong.)

查看更多
SAY GOODBYE
4楼-- · 2019-01-21 00:25

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.

查看更多
登录 后发表回答