Keys in NSDictionary can be duplicated?

邮差的信 提交于 2019-12-05 21:38:19

问题


From what I have read, keys in dictionaries are unique.

Consider this code:

NSMutableDictionary *mydic = [NSMutableDictionary dictionary];

[mydic setObject:@"value1" forKey:@"key1"]; 
[mydic setObject:@"value1" forKey:@"key1"];
[mydic setObject:@"value1" forKey:@"key1"];

Why can I run this without any error? What should I do to avoid duplicate keys?


回答1:


Yes keys are unique. Calling -setObject:forKey: with an existing key overrides the old value — it sets values, not adds values. You can check that:

[mydict setObject:@"1" forKey:@"key1"];
[mydict setObject:@"2" forKey:@"key1"];
NSLog(@"%@", mydict);

If you don't want existing items to be overridden, check if it exists with -objectForKey::

@implementation NSMutableDictionary (AddItem)
-(void)addObjectWithoutReplacing:(id)obj forKey:(id)key {
   if ([self objectForKey:key] == nil)
      [self setObject:obj forKey:key];
}
@end


来源:https://stackoverflow.com/questions/6807953/keys-in-nsdictionary-can-be-duplicated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!