Search code examples
iosiphoneobjective-cfull-text-searchnsmutabledictionary

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.


Solution

  • 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.