Question

I need to search the index of a string from NSMutableArray. I have implemented the code & which works perfect, but I need to increase the searching speed than this.

I have used the following code:

NSIndexSet *indexes = [mArrayTableData indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
    NSString *s = (NSString*)obj;
    NSRange range = [s rangeOfString: txtField.text options:NSCaseInsensitiveSearch];
    if(range.location == 0)//
        return range.location != NSNotFound;
    return NO;
}];

NSLog(@"indexes.firstIndex =%d",indexes.firstIndex);
Was it helpful?

Solution

There is a method indexOfObject

NSString *yourString=@"Your string";
NSMutableArray *arrayOfStrings = [NSMutableArray arrayWithObjects: @"Another strings", @"Your string", @"My String", nil];

NSInteger index=[arrayOfStrings indexOfObject:yourString];
if(NSNotFound == index) {
    NSLog(@"Not Found");
}

OTHER TIPS

If you only want one index (or just the first one if there are multiples), you can use the singular version of the method you posted. You also don't need the if clause:

NSInteger index = [mArrayTableData indexOfObjectPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop){
        return [obj.lowercaseString isEqualToString:txtField.text.lowercaseString];
    }];

If you want to find strings that start with the search string, just replace isEqualToString: with hasPrefix:. With a large search set, this appears to be about twice as fast as the method you posted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top