Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Insensitive Search in NSMutableDictionary

HI, I have a NSMutableDicitionary contains both lowercase and uppercase keys. So currently i don't know how to find the key in the dictionary irrespective key using objective c.

like image 998
Vignesh Babu Avatar asked May 26 '11 07:05

Vignesh Babu


2 Answers

Categories to the rescue. Ok, so it's an old post...

@interface NSDictionary (caseINsensitive)
-(id) objectForCaseInsensitiveKey:(id)aKey;
@end


@interface NSMutableDictionary (caseINsensitive)
-(void) setObject:(id) obj forCaseInsensitiveKey:(id)aKey ;
@end


@implementation NSDictionary (caseINsensitive)

-(id) objectForCaseInsensitiveKey:(id)aKey {
    for (NSString *key in self.allKeys) {
        if ([key compare:aKey options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            return [self objectForKey:key];
        }
    }
    return  nil;
}
@end


@implementation NSMutableDictionary (caseINsensitive)

-(void) setObject:(id) obj forCaseInsensitiveKey:(id)aKey {
    for (NSString *key in self.allKeys) {
        if ([key compare:aKey options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            [self setObject:obj forKey:key];
            return;
        }
    }
    [self setObject:obj forKey:aKey];
}

@end

enjoy.

like image 150
unsynchronized Avatar answered Nov 04 '22 10:11

unsynchronized


Do you have control over the creation of the keys? If you do, I'd just force the keys to either lower or upper case when you're creating them. This way when you need to look up something, you don't have to worry about mixed case keys.

like image 42
csano Avatar answered Nov 04 '22 09:11

csano