Search code examples
iphoneobjective-ciosipadnsarray

How retrieve an index of an NSArray using a NSPredicate?


I would know how retrieve an index of an NSArray using a NSPredicate ?

NSArray *array = [NSArray arrayWithObjects:
                  @"New-York City",
                  @"Washington DC",
                  @"Los Angeles",
                  @"Detroit",
                  nil];

Which kind of method should I use in order to get the index of "Los Angles" by giving only a NSString?
NB: @"Los An" or @"geles" should return the same index.


Solution

  • Using NSPredicate you can get array of strings that contain your search string (it seems there's no built-in method to get just element indexes):

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchString];
    NSArray *filteredArray = [array filteredArrayUsingPredicate: predicate];
    

    You can get only indexes using indexesOfObjectsPassingTest: method:

    NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
       NSString *s = (NSString*)obj;
       NSRange range = [s rangeOfString: searchString];
       return range.location != NSNotFound;
    }];
    

    If you want to get just one element containing your string you can use similar indexOfObjectPassingTest: method for that.