tags:

views:

9049

answers:

4

I would like to be able to check the type of an object

+18  A: 

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
How would I check for equality with an object of type "AnObject" for example?
Dimitris
"if ([myObject class] == [AnObject class])" or, as suggested by Jon Skeet and zoul: "if ([myObject isKindOfClass:[AnObject class]])"
mouviciel
Unless I'm mistaken, the answer here requires an *exact* type match, rather than the "right type or subclass" match provided by instanceof.
Jon Skeet
You are right, I've updated my answer.
mouviciel
+11  A: 

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  A: 

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
A: 

Zoul - why is using class type checking considered bad? Is this not good defensive programming or are you arguing it should be unnecessary?

Ian Kershaw