2008 07 10Telling classes from instances
objectis a class or an instance, and the runtime will automatically call class (
+) or instance (
-) methods. If comes the time where you need to tell them apart, a simple way is to check if an object matches its class :
// A class id object1 = NSClassFromString(@"NSApplication"); // An instance id object2 = [object1 sharedApplication]; // Telling instances from classes … // Evaluates to YES isClass = object1 == [object1 class]; // Evaluates to NO isClass = object2 == [object2 class];Or did I miss some obvious "already there" method ?
why not implement a method: +isClass and -isClass or +isInstance and -isInstance in Object?
nothing to compare then, just return a YES and a NO in the right methods ;-)
BOOL isClass = ![object1 isMemberOfClass:[object1 class]];
Seems like class is not a member of itself ;)... However docs say:
"Class objects may be compiler-created objects but they still support the concept of membership. Thus, you can use this method to verify that the receiver is a specific Class object."
Second, total hack:
BOOL isClass = (NSStringFromClass(object1) != nil);
@Karsten You get my vote for pragmatic programming :)
@Dmitry Thanks for the hack ! So there is no official method. Frustrating since NSStringFromClass seems to be using the unofficial one …
Ah. In hindsight, I misread your article :) Thanks for clarifying
Classes are objects. They are of class Class. As mentioned before, you rarely need to actually know to what class an object belongs; just ask it
-conformsToProtocol:. But if you really need to know if you're dealing with an object of a specific class
Foo, just ask
[obj isMemberOfClass:[Foo class]]. Putting two and two together, if you want to know if a specific object
obj is actually a class, ask
[obj isMemberOfClass:[Class class]].
If classes are objects, where are they defined ? I didn't find
in the headers. That's what I don't get about classes : they do behave like objects but Class is defined as a struct !?
There is very rarely a need to know your class.
There are two places I know of where you (sort of) need to know a class.
1) You're working on backwards compatibility, some methods are only supported on newer versions of the OS. Use respondsToSelector: to figure out if your object is OK
2) You want to verify your object can behave a certain way. All you need to determine is if it conforms to a specific protocol - use conformsToProtocol:
That way, any implementation that satisfies those less stringent requirements will still work - you're not tied to your original choice of class.