In Objective-C, what is the equivalent of Java's “instanceof” keyword?

前端 未结 3 601
走了就别回头了
走了就别回头了 2020-12-12 12:29

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

相关标签:
3条回答
  • 2020-12-12 12:42

    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.)

    0 讨论(0)
  • 2020-12-12 12:53

    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.

    0 讨论(0)
  • 2020-12-12 13:05

    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.

    0 讨论(0)
提交回复
热议问题