Recently I came across an interesting issue, while working with some Class objects.
As you know every class in Objective-C is an object as well, which brings us to some curious options when trying to check if a given class variable is actually derived from a given class.
I know what you’re thinking – “Just use isKindOfClass, stupid.” That’s what I did.
Let’s see what that gives us:
Class imageViewClass = [UIImageView class];
BOOL trueOrFalse = [imageViewClass isKindOfClass:[UIView class]];
This, interestingly enough, returns false.
Well why is that?
Here’s what the docs say about 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 a class returns false because it is meant to be sent to an instance of a class, not to the class itself.
So the right thing to do here is use isSubclassOfClass: , which returns what we’re looking for.
All of the classes are immutable constants, basically they’re like string literals – all the objects that are an instance of a given class share the same Class object (iOS only, not true on OS X), thus you can use the equals operator (==) to check if two class objects are the same.
You should never do that.
Though it’ll work for classes that are the same, the right way here is to use the provided comparison methods, since some things in the framework often masquerade as a given class, even though they’re not and the comparison will fail (KVO, class clusters) .
Well, that’s it for today.
I’ve got some more articles coming your way, as I’m working on some pretty interesting stuff that I’d like to share with you guys.
Until next time!