tags:

views:

1573

answers:

2

Hi,

How do I test whether an object is an instance of a particular class in objective c? Let's say I want to see if object a is an instance of class b, or class c, how do I go about doing it? Thanks!

+9  A: 

you can use

NSString *className = NSStringFromClass([myObject class]); 

on a NSObject

Henrik P. Hessel
Please don't use -className. It's API for use with scripting, see: <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/className" title="NSObject Documentation">NSObject docs</a>The correct way to do this is:NSString *className = NSStringFromClass([myObject class]);
Jonathan Dann
thanks, correct!
Henrik P. Hessel
+7  A: 

To test if object is an instance of class a:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of 
// given class or an instance of any class that inherits from that class.

or

[yourObject isMemberOfClass:[a class]]
 // Returns a Boolean value that indicates whether the receiver is an instance of a 
 // given class.

To get object's class name you can use

   const char* className = class_getName([yourObject class]);
Vladimir