objective-ciosnsdictionarykey-valuecase-insensitive

NSDictionary case insensitive objectForKey:


NSDictionary has objectForKey but it's case-sentive for keys. There is No function available like

- (id)objectForKey:(id)aKey options:(id) options;

where in options you can pass "NSCaseInsensitiveSearch"

To get key's from NSDictionary which is case-insesitive one can use the following code written below.


Solution

  • This isn't included for a couple of reasons:

    1. NSDictionary uses hash equality, and for pretty much any good hashing algorithm, any variation in the source string results in a different hash.

    2. More importantly, NSDictionary keys are not strings. Any object that conforms to NSCopying can be a dictionary key, and that includes a whole lot more than strings. What would a case-insensitive comparison of an NSNumber with an NSBezierPath look like?

    Many of the answers here offer solutions that amount to transforming the dictionary into an array and iterating over it. That works, and if you just need this as a one-off, that's fine. But that solution is kinda ugly and has bad performance characteristics. If this were something I needed a lot (say, enough to create an NSDictionary category), I would want to solve it properly, at the data structure level.

    What you want is a class that wraps an NSDictionary, only allows strings for keys and automatically lowercases keys as they are given (and possibly also remembers the original key if you need a two-way mapping). This would be fairly simple to implement and is a much cleaner design. It's too heavy for a one-off, but if this is something you're doing a lot, I think it's worth doing cleanly.