IPhone, how to check the type of object?

I want to check the type of an object. How can i do this?

Scenario: I get an object. If this object is type A, perform some operations. If it is type B, perform some operations. Currently, the object type is C, which is the parent of A and B.

I have two classes AViewController and BViewController . The object I get in the UIViewController . Now, how to check if an object is an AViewController or a BViewController ?

+61
iphone uiviewcontroller uiview
Sep 02 '09 at 14:42
source share
3 answers
 if([some_object isKindOfClass:[A_Class_Name class]]) { // do somthing } 
+152
Sep 02 '09 at 14:50
source share

NSObject has several methods that allow you to validate classes.

First there is a -class that will return the class of your object. This will return either an AViewController or a BViewController.

Then there are two methods: -isKindofClass: and isMemberOfClass:

-isKindofClass: will compare the receiver with the class passed as an argument and return true or false based on whether the class is the same type or subclass of this class.

-isMemberOfClass: compares the receiver with the class passed as an argument, and returns true or false based on whether the class is exactly the same class as the given class.

+44
Sep 02 '09 at 14:51
source share

A more general pattern in Objective-C is to check if the object meets the methods that interest you. Example:

 if ([object respondsToSelector:@selector(length)]) { // Do something } if ([object conformsToProtocol:@protocol(NSObject)]) { // Do something } 
+3
Sep 02 '09 at 15:17
source share



All Articles