views:

395

answers:

3

Hello.

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.

A: 

I'd say create a second dictionary. After you load from the property set, loop through that dictionary and insert objects into the second dictionary. Convert the keys to lowercase as you go. Then release the first dictionary.

Mike
+2  A: 

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
drawnonward
for god's sake, you have the length of the current dictionary, thus the final dictionary... [NSMutableDictionary dictionaryWithCapacity:0] with the actual size!!! (eg. [NSMutableDictionary dictionaryWithCapacity:self.count])
Jared P
+1  A: 

Although I'm still not clear on what you want, this loop with search for keys case insensitively. Getting the value of that key is then trivial.

for key in dict
{
    if ([key caseInsensitiveCompare: @"Whatever"] == NSOrderedSame)
        NSLog(@"They are equal.");
}
jshier