Fevicks
Fevicks

Reputation: 223

Search index of NSMutableArray

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);

Upvotes: 1

Views: 1501

Answers (2)

rdelmar
rdelmar

Reputation: 104082

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.

Upvotes: 2

Alexey
Alexey

Reputation: 7247

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");
}

Upvotes: 3

Related Questions