193

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?

Rok Strniša
  • 6,781
  • 6
  • 41
  • 53
Dimitris
  • 682
  • 3
  • 14
  • 19

3 Answers3

273

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.

mouviciel
  • 66,855
  • 13
  • 106
  • 140
37

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

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

zoul
  • 102,279
  • 44
  • 260
  • 354
  • 3
    Just copying from the "answer" below: "@Zoul - why is using class type checking considered bad? Is this not good defensive programming or are you arguing it should be unnecessary?" – Dan Rosenstark Dec 05 '10 at 16:19
  • 1
    Aha, thanks. One problem is that objects do not have to be of the class you are expecting. During testing it’s quite common to pass a class stub that honours the interface, but has a different class. Or when you observe value changes using KVO there’s certain magic done with the classes. Both cases are quite legit and both are easily broken if your code does explicit class checks. Switching behaviour on class is poor OO design, tightly coupled and hard to extend. I am not saying there is no legit use case for class checks, but you should think twice before doing it. – zoul Dec 05 '10 at 18:05
  • @zoul In that specific case this would be just plain inexperience, one would more likely use `+ (BOOL)conformsToProtocol:(Protocol *)aProtocol`. – EricLeaf May 06 '13 at 19:37