Search code examples
iphonexcodensmutabledictionarycase-insensitive

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 objectForKey:@"my key"] == nil) as well as ([[myDictionary allKeys] containsObject:@"my key"]) both of which are case sensitive.

Thanks,

John


Solution

  • Here's what I would do since NSDictionary doesn't support case-insensitive key lookups.

    1. Use the allKeys method of NSDictionary to retrieve the array of keys from the dictionary.
    2. Use an NSPredicate with a case insensitive search to filter the array of keys.
    3. Use the resulting array of keys (there may be more than one) to retrieve the value objects from the dictionary.