问题
I'm trying to use a class as a key in an NSDictionary
. I looked at the answer to this question and what I have is pretty much the same; I'm using setObject: forKey:
. However, XCode complains, saying Incompatible pointer types sending 'Class' to parameter of type 'id<NSCopying>'
. The call I have is:
[_bugTypeToSerializerDictionary setObject: bugToStringSerializer
forKey: [bugToStringSerializer serializedObjectType]];
bugToStringSerializer
is an instance of BugToStringSerializer
whose concrete implementations implement serializedObjectType
. An example of a concrete implementation looks like this:
- (Class) serializedObjectType {
return [InfectableBug class];
}
What am I doing wrong here?
回答1:
(It seems that classes do conform to NSCopying
, however their type is not id <NSCopying>
.) Edit: classes do not conform to protocols. Of course the essential is that classes respond to the copy
and copyWithZone:
messages (and that's why you can safely ignore the warning in this case). Their type is still not id <NSCopying>
.) That's why the compiler complains.
If you really don't want that ugly warning, just perform an explicit type conversion:
[dictionary setObject:object forKey:(id <NSCopying>)someClass];
回答2:
Aha,I just fixed the bug in my project.
use this:
NSStringFromClass([Someclass class]);
回答3:
The other answers are certainly helpful, but in this case it probably makes more sense to just use an NSMapTable, which does not copy the key unlike NSDictionary, and just retains it with a strong pointer (by default, although this can be changed).
Then you can just use your original code with no modifications.
NSMapTable *_bugTypeToSerializerDictionary = [NSMapTable new];
...
[_bugTypeToSerializerDictionary setObject: bugToStringSerializer
forKey: [bugToStringSerializer serializedObjectType]];
It's less hacky, and is clearer at conveying programmer intent.
For extra style points you could give the instance variable a slightly more fitting name like_bugTypeToSerializerMap
.
回答4:
This is my usual code:
@{
(id)[MyClass1 class] : @1,
(id)[MyClass2 class] : @2,
(id)[MyClass3 class] : @3,
(id)[MyClass4 class] : @4,
};
But recently I've discovered this approach:
@{
MyClass1.self : @1,
MyClass2.self : @2,
MyClass3.self : @3,
MyClass4.self : @4,
};
来源:https://stackoverflow.com/questions/12525324/unable-to-use-class-as-a-key-in-nsdictionary