You could do that, but since each object can retrieve its own class, as you pointed out above, why do you need to store it separately? Just retrieve objects into an id object and call the +class method on the objects in the collection to find out what they are. And use the NSStringFromClass() if you need a string for the class name.Does anybody know a good way to to store the Class type (as returned by +class) in a Cocoa collection?
The best solution I can think of is to create a simple object wrapper to store the variable ... is there a better way?
NSMutableArray *array = [NSMutableArray array];
[array addObject:[NSString class]];
[array addObject:[NSArray class]];
[array addObject:[NSDictionary class]];
[array addObject:[NSData class]];
[array addObject:[NSNumber class]];
No need to convert to NSString or write a wrapper. It should work just like a standard object.
You could do that, but since each object can retrieve its own class, as you pointed out above, why do you need to store it separately? Just retrieve objects into an id object and call the +class method on the objects in the collection to find out what they are. And use the NSStringFromClass() if you need a string for the class name.
I must admit I haven't actually tried this, I just assumed it wouldn't work!
My god, it works! I am impressed. My only remaining question is ... how??
[MyClass class] returns the class object. In obj-C a class is also an object (unlike C++). Since it is an object, you can store it in an array. There really is nothing special about it.
I do understand that, I'm just wondering why the runtime doesn't raise an exception when trying to call the method retain on the class object. Is there a (dummy) class method declared by NSObject called retain? If so, it's not documented. Am I missing something?
Thanks for the link by the way.
The NSObject protocol declares retain as an instance method, not a class method! Or at least it appears to...
The runtime raises an exception when you send a message to a method that doesn't exist. Try it yourself - find one of your own objects, and send a message to invoke an instance method to the class. For example:
[FooClass doFoo];
You will get an exception. However, attempt to call any instance method declared by NSObject and nothing will happen:
[FooClass retain];
Why is that? Is NSObject declaring every single one of these methods as class methods as well?
No, [MyClass class] returns a pointer to the class object itself.
I've found the answer: "Instance methods defined in the root class can be performed both by instances and by class objects."
It's annoying that Apple doesn't mention this in the NSObject reference.
[[NSObject class] release];