Using class as key in NSDictionary

前端 未结 7 1421
挽巷
挽巷 2020-12-28 14:00

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:



        
7条回答
  •  独厮守ぢ
    2020-12-28 14:46

    You're using setValue:forKey: which only takes NSStrings as keys. you should be using setObject:forKey: instead. A class object (pointers to class objects can be passed as type Class) is a full-fledged Objective-C object (a class object is an instance of its meta-class, and you can use all the NSObject methods 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.

提交回复
热议问题