I would like to be able to check the type of an object
views:
9049answers:
4Try [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.
From Wikipedia:
In Objective-C, for example, both the generic
Object
andNSObject
(in Cocoa/OpenStep) provide the methodisMemberOfClass:
which returnstrue
if the argument to the method is an instance of the specified class. The methodisKindOfClass:
analogously returns true if the argument inherits from the specified class.
isKindOfClass:
would be closest to instanceof
, by the sounds of it.
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 - why is using class type checking considered bad? Is this not good defensive programming or are you arguing it should be unnecessary?