How to determine if a Key already exists in a NSMutableDictionary ignoring case
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 objectForKe开发者_运维知识库y:@"my key"] == nil) as well as ([[myDictionary allKeys] containsObject:@"my key"]) both of which are case sensitive.
Thanks,
John
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
and MY 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).
Here's what I would do since NSDictionary doesn't support case-insensitive key lookups.
- Use the allKeys method of NSDictionary to retrieve the array of keys from the dictionary.
- Use an NSPredicate with a case insensitive search to filter the array of keys.
- Use the resulting array of keys (there may be more than one) to retrieve the value objects from the dictionary.
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):
{
"my key":
{
"original":"My KeY",
"content":"Original content"
},
"other key":
{
"original":"OthEr KeY",
"content":"Original content"
}
}
精彩评论