NSDictionary中的键可以复制吗? [英] Keys in NSDictionary can be duplicated?

查看:263
本文介绍了NSDictionary中的键可以复制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我所阅读的内容,字典中的键是唯一的。

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

请考虑以下代码:

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?

推荐答案

是的键是唯一的。调用 -setObject:forKey:使用现有键覆盖旧值 - 设置值,而不是添加值。您可以检查:

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);

如果不希望覆盖现有项目,请检查其是否存在 -objectForKey:

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

这篇关于NSDictionary中的键可以复制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆