iPhone how to check the type of an Object?

IphoneUiviewUiviewcontroller

Iphone Problem Overview


I want to check the type of an Object. How can I do that?

The scenario is I'm getting an object. If that object is of type A then do some operations. If it is of type B then do some operations. Currently the type of the object is C that is parent of A and B.

I have two classes AViewController and BViewController. The object I'm getting in UIViewController. Now how to check whether the object is AViewController or BViewController?

Iphone Solutions


Solution 1 - Iphone

if([some_object isKindOfClass:[A_Class_Name class]])
{
    // do somthing
}

Solution 2 - Iphone

There are some methods on NSObject that allow you to check classes.

First there's -class which will return the Class of your object. This will return either AViewController or BViewController.

Then there's two methods, -isKindofClass: and isMemberOfClass:.

-isKindOfClass: will compare the receiver with the class passed in as the argument and return true or false based on whether or not the class is the same type or a subclass of the given class.

-isMemberOfClass: will compare the receiver with the class passed in as the argument and return true or false based on whether or not the class is strictly the same class as the given class.

Solution 3 - Iphone

A more common pattern in Objective-C is to check if the object responds to the methods you are interested in. Example:

if ([object respondsToSelector:@selector(length)]) {
    // Do something
}

if ([object conformsToProtocol:@protocol(NSObject)]) {
    // Do something
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiong.revolutionView Question on Stackoverflow
Solution 1 - IphonePavel YakimenkoView Answer on Stackoverflow
Solution 2 - IphoneJasarienView Answer on Stackoverflow
Solution 3 - IphonerpetrichView Answer on Stackoverflow