开发者

Keys in NSDictionary can be duplicated?

开发者 https://www.devze.com 2023-03-22 18:58 出处:网络
From what I have read, keys in dictionaries are unique. Consider this 开发者_JAVA百科code: NSMutableDictionary *mydic = [NSMutableDictionary dictionary];

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

Consider this 开发者_JAVA百科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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消