63

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 andBViewController. The object I'm getting in UIViewController. Now how to check whether the object is AViewController or BViewController?

Arulkumar
  • 12,966
  • 14
  • 47
  • 68
g.revolution
  • 11,962
  • 23
  • 81
  • 107

3 Answers3

152
if([some_object isKindOfClass:[A_Class_Name class]])
{
    // do somthing
}
Pavel Yakimenko
  • 3,234
  • 4
  • 28
  • 33
  • 6
    The post from @Jasarien is more specific. For example comparing if an object is KindOfClass [UIView class] will return you even all UIImageViews, UIImages, UIRoundRectButtons..... So in this case "isMemberOfClass might be the better solution. – Alex Cio Jun 20 '13 at 09:08
45

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.

Jasarien
  • 58,279
  • 31
  • 157
  • 188
3

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
}
rpetrich
  • 32,196
  • 6
  • 66
  • 89
  • This true, but not very helpful in this case. The two objects the questioner is interested in are both subclasses of a particular view controller. Each one may implement the same method, but behave differently. So he/she needs to know which subclass they're dealing with. – Jasarien Sep 02 '09 at 15:20
  • If that's the case, you should probably refactor your design. isKindOfClass: will definitely work, but isn't usually very maintainable in the long run. – rpetrich Sep 02 '09 at 23:47