views:

1363

answers:

3

HI , i am new to iPhone. i want to check the type of an Object. how i will do that ... the scenerio is i m getting an object . if that object is of type A then do something .. if it is of type B then do something .. 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 . how to check that ???

+9  A: 
if([some_object isKindOfClass:[A_Class_Name class]])
{
    // do somthing
}
Pavel Yakimenko
+3  A: 

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
+1  A: 

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
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
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