Case insensitive indexOfObject for NSArray

耗尽温柔 提交于 2019-12-02 00:39:55

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.

RamaKrishna Chunduri

questioner ,

it's an excellent idea of writing a category in NSArray to do this . it helped me a lot in my app. However there's a pretty much easier way to do the this instead of iterating the array.


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

@implementation NSArray (CaseInsensitiveIndexing)

- (NSUInteger)indexOfCaseInsensitiveString:(NSString *)aString 
{
   return [self indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) 
   { 
       return [[obj lowercaseString] isEqualToString:[aString lowercaseString]]; 
   }];
}   

@end

Note :indexOfObjectPassingTest works with IOS 4.0 only

No custom category needed:

[myArray indexOfObjectPassingTest:^(NSString *obj, NSUInteger idx, BOOL *stop){
    return (BOOL)([obj caseInsensitiveCompare:term] == NSOrderedSame);
}]

I haven't tried it but you should be able to do this by filtering the array with an NSPredicate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!