I’m writing a contextual ‘factory’ that will maintain a dictionary of converter/acting objects which inherit from some Converter class. This class has a method:
- (Class)classResponsibility
Or something similar, such that a StringConverter class would implement the method as:
- (Class)classResponsibility { return [NSString class]; }
Then to store that converter in the dictionary, I had hoped on doing something like:
[converters setValue:stringConverter forKey:[stringConverter classResponsibility]];
But the compiler complains that the type ‘Class’ is an invalid parameter type for argument 2 of the setValue:forKey: method. I had wanted to avoid setting the key as the Class’s name (‘NSString’), but if that’s the best solution than I’ll go with it.
You’re using
setValue:forKey:which only takesNSStrings as keys. you should be usingsetObject:forKey:instead. A class object (pointers to class objects can be passed as typeClass) is a full-fledged Objective-C object (a class object is an instance of its meta-class, and you can use all theNSObjectmethods on a class object; read more about meta-classes here), so they can be used anywhere objects are used.Another requirement for keys of a dictionary is that they support copying (i.e. have the
copyWithZone:method. Do class objects support this method? In fact, it does. The NSObject class defines a class method+copyWithZone:, whose documentation explicitly says that it ‘lets you use a class object as a key to an NSDictionary object’. I think that’s the answer to your question.