How do I test which class an object is in Objective-C?

futureelite7 picture futureelite7 · Jan 13, 2010 · Viewed 145.2k times · Source

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?

Answer

Vladimir picture Vladimir · Jan 13, 2010

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 NSStringFromClass function:

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

or c-function from objective-c runtime api:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);

EDIT: In Swift

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}