Peter Lapisu
Peter Lapisu

Reputation: 20975

isKindOfClass on two classes (not instances)

Class named B inherits from A (B : A)

[[B class] isKindOfClass:[A class]]

returns NO

doing

[[B new] isKindOfClass:[A class]]

returns YES

so the left caller must be an instance, but how to do the same with a Class ?

Upvotes: 4

Views: 2612

Answers (2)

Nicolas
Nicolas

Reputation: 933

- (BOOL)isKindOfClass:(Class)aClass

is indeed an instance method (note the -) and won't work on the class

+ (BOOL)isSubclassOfClass:(Class)aClass

is a class method (note the +) and that's what you're looking for.

But wait ! NSObject Class Reference tells us “Refer to a class only by its name when it is the receiver of a message. In all other cases [...] use the class method.”

So you will use :

[B isSubclassOfClass:[A class]] 

Upvotes: 21

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

A Class is like an object, it's able to respond to many messages, to print a description and also a Class has a class property. But the class property points back to the class itself, that's why if you do something like:

NSLog(@"%@",[[NSObject class]class]);

You get "NSObject". You think to have a NSObject instance, but instead you haven't one.

Class overrides isKindOfClass: and isMemberOfClass:, that's why [[NSObject isKindOfClass: [NSObject class]] returns NO, because NSObject is a Class, not a NSObject instance.

The way to test it is to call the method on instances, or like already posted in the comments to use Objective-C runtime.

Upvotes: 0

Related Questions