Joris Weimar
Joris Weimar

Reputation: 4921

How to determine whether class B is a subclass of class A?

It seems that if you develop for Mac OS, NSObject has the isSubclassOfClass method. But when I check the iOS class reference for the same class, it does not have the method (and Xcode complains about the method).

My current solutions is to put a method -(void)iAmClassB in there, and perform a respondsToSelector:iAmClassB, but that seems contrived. Am I missing something?

Upvotes: 28

Views: 17265

Answers (2)

It is available from iOS 2.0 and later version SDK

if ([ClassB isSubclassOfClass:[ClassA class]]) {


    NSLog(@"yes ClassB is SubclassOfClass of ClassA");

}       

Documentation:

isSubclassOfClass:

Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.

   + (BOOL)isSubclassOfClass:(Class)aClass

Parameters

aClass

A class object.

Return Value

YES if the receiving class is a subclass of—or identical to—aClass, otherwise NO.

Availability

Available in iOS 2.0 and later.

Upvotes: 62

Yuji
Yuji

Reputation: 34185

id a= ...;
if([a isKindOfClass:[A class]]){
     ...
}

should do the job. You rarely needs to see if it's really a sub class. See here.

Upvotes: 5

Related Questions