Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

People also ask

How do you declare a class in Objective-C?

In Objective-C every new class is declared with an @interface, followed by the custom class name, followed by a colon and ending with the name of the superclass. In this example we've used NSObject as our superclass. All classes are derived from NSObject since its the base class.

How do you declare an object in Objective-C?

Creating a new object in Objective-C is usually a two-step process. First, memory has to be allocated for the object, then the object is initialized with proper values. The first step is accomplished through the alloc class method, inherited from NSObject and rarely, if ever, overridden.

Is kind of 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. Required.


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
}

You also can use

NSString *className = [[myObject class] description]; 

on any NSObject


What means about isKindOfClass in Apple Documentation

Be careful when using this method on objects represented by a class cluster. Because of the nature of class clusters, the object you get back may not always be the type you expected. If you call a method that returns a class cluster, the exact type returned by the method is the best indicator of what you can do with that object. For example, if a method returns a pointer to an NSArray object, you should not use this method to see if the array is mutable, as shown in the following code:

// DO NOT DO THIS!
if ([myArray isKindOfClass:[NSMutableArray class]])
{
    // Modify the object
}

If you use such constructs in your code, you might think it is alright to modify an object that in reality should not be modified. Doing so might then create problems for other code that expected the object to remain unchanged.


If you want to check for a specific class then you can use

if([MyClass class] == [myClassObj class]) {
//your object is instance of MyClass
}