Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary: convert NSString keys to lowercase to search a string on them

I'm developing an iPhone application.

I use a NSDictionary to store city's names as key, and population as value. I want to search the keys using lowercase.

I've using this:

NSDictionary *dict;

[dict objectForKey:[[city stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] lowercaseString]];

But, it doesn't work.

I know, I can do a for, convert keys to lowercase and compare with city.

Is there any other way to do that? Maybe, with a NSDictionary method.

UPDATE
The NSDictionary is loaded from a property list.

Thank you.

like image 553
VansFannel Avatar asked Oct 20 '25 14:10

VansFannel


1 Answers

I use this method in an NSDictionary category.

@implementation NSDictionary (MyCategory)
- (NSDictionary *)dictionaryWithLowercaseKeys {
    NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:0];
    NSString *key;

    for (key in self) {
        [result setObject:[self objectForKey:key] forKey:[key lowercaseString]];
    }

    return result;
}
@end
like image 157
drawnonward Avatar answered Oct 23 '25 09:10

drawnonward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!