如何确定 NSMutableDictionary 中是否已存在 Key 忽略大小写
在将新键值对添加到 NSMutableDictionary 之前,我需要确定它的键是否唯一。我怎样才能在不区分大小写的情况下做到这一点?例如,如果字典中存在“My Key”、“MY KEY”或“my key”等,则不应验证名为“my key”的新密钥。
我尝试过 ([myDictionary objectForKey:@"my key"] == nil) 以及 ([[myDictionary allKeys] containsObject:@"my key"]) ,两者都区分大小写。
谢谢,
约翰
I need to determine if the key of a new key value pair is unique before adding it to a NSMutableDictionary. How can I do this with case insensitivity? For example a new key called "my key" should not be validated if "My Key","MY KEY", or "my key", etc. exists in the dictionary.
I have tried ([myDictionary objectForKey:@"my key"] == nil) as well as ([[myDictionary allKeys] containsObject:@"my key"]) both of which are case sensitive.
Thanks,
John
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好的解决方案是不在字典中存储区分大小写的键。任何类型的搜索都会非常慢。
即
[myDict setObject: foo forKey: [aKey lowercaseString]]
;这假设字典不需要区分
My Key
和MY KEY
。如果确实如此,您最好使用上述内容并根据需要使用一个集合作为进一步区分所述键的值(尽管这会开始让我质疑数据结构是否真正是最佳的)。The best solution is to not store case sensitive keys in your dictionary. Any kind of a search is going to be very slow.
I.e.
[myDict setObject: foo forKey: [aKey lowercaseString]]
;This assumes the dictionary doesn't need to differentiate between
My Key
andMY KEY
. If it does, you are still better off using the above and having a collection as the value that further differentiates said key, as necessary (though this would start to make me question whether the data structure is truly optimal).这是我要做的,因为 NSDictionary 不支持不区分大小写的键查找。
Here's what I would do since NSDictionary doesn't support case-insensitive key lookups.
始终将按键设置为小写不是更容易吗?这将确保小写的新密钥将与另一个密钥冲突,从而表明该密钥已被使用。
如果字符串的实际大小写很重要,则使用小写字符串作为键,并将其存储为值的一部分,例如(Python/JSON 字典表示法):
Wouldn't be easier to always set the keys to lowercase? This would ensure that a lowercase new key will clash with another one, thus, indicating that the key is used.
If the actual casing of the string matters, then use the lowercase string as the key, and store it as part of the value, say (Python/JSON dictionary notation):