iPhone iOS How to compare the Class object to another class object?


I have a Class reference defined in one of classes working with:

Class _objectClass;

     if([self.objectClass isSubclassOfClass:[NSManagedObject class]])
           //does not get called

How can I check what kind of Class I'm dealing with?

UPDATE: sorry autocomplete did not show me that isKindOfClass: was available. I'm testing that now

There are two methods you're interested in:

isKindOfClass: asks the receiver if it is a class or a subclass, where as isMemberOfClass: asks the receiver if it is the class, but not a subclass. For instance, let's say you have your NSManagedObject subclass called objectClass.

 if([self.objectClass isKindOfClass:[NSManagedObject class]]) {
     // This will return YES
 else if ([self.objectClass isMemberOfClass:[NSManagedObject class]]) {
     // This will return NO

The first statement returns YES (or true, or 1) because objectClass is a subclass of NSManagedObject. The second statement returns NO (or false, or 0) because while it is a subclass, it is not the class itself.

UPDATE: I'd like to update this answer to bring light to a comment below, which states that this explanation is wrong because the following line of code:

if ([self.class isKindOfClass:self.class])

would return false. This is correct, it would return false. But this example is wrong. Every class that inherits from NSObject also conforms to the NSObject protocol. Within this protocol is a method called class which "returns the class object for the receiver's class". In this case, self.class returns whatever class object self is. However, from the documentation on isKindOfClass: -

Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.

thus, sending this message to self.class (which is a class) returns false because it is meant to be sent to an instance of a class, not to a class itself.

If you change the example to

if([self isKindOfClass:self.class])

You will get YES (or true, or 1).

My answer here presumes that self.objectClass is an accessor to an instance named objectClass. Sure, it's a terrible name for an instance of a class, but the question was not "how do I name instances of classes".