tags:

views:

345

answers:

1

Is there an easy way to do a case insensitive lookup in an NSArray of NSStrings? Reference for NSArray mentions sorting case insensitively but nothing about lookup.

I can easily write my own fn to do it but would like to know if there's an easier way.

+4  A: 

I don't know of any built-in way to do this. However, it would be trivial to write a category on NSArray which does this:

@interface NSArray (CaseInsensitiveIndexing)
- (NSUInteger)indexOfCaseInsensitiveString:(NSString *)aString;
@end

@implementation NSArray (CaseInsensitiveIndexing)

- (NSUInteger)indexOfCaseInsensitiveString:(NSString *)aString {
    NSUInteger index = 0;
    for (NSString *object in self) {
        if ([object caseInsensitiveCompare:aString] == NSOrderedSame) {
            return index;
        }
        index++;
    }
    return NSNotFound;
}   

@end

Of course, you'd probably want to do a bit of type checking to make sure the array's items actually are NSStrings before you call -caseInsensitiveCompare:, but you get the idea.

Matt Ball
Thanks Matt. That's pretty much what I did, but just in a local function. I'm pretty new to ObjC so pardon my ignorance, but is there any advantage to how you've iterated the array vs a simple "for (NSUInteger i=0; i<self.count; i++) ... [self objectAtIndex:i]"??
cantabilesoftware
No, both approaches are fine. I tend to do things this way, since certain compilers (or even certain modes of certain compilers) don't allow the variable declaration within the for loop. Since you can never be sure what flags people are passing to their compilers, I try to make sure that any code I post here should compile for everyone.
Matt Ball