John Baum
John Baum

Reputation: 3331

Searching on the properties of objects in an array

I have an NSArray of objects with properties such as firstName, lastName, clientID etc. and i would like to perform a search on the array based on a search keyword. This keyword must be checked against the first name and the last name properties and return a subset of the original array that contains only those objects whose first/last name contain the search term. Is there any efficient/fast way to do this?

Upvotes: 2

Views: 3537

Answers (3)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

I think your looking for -indexesOfObjectsPassingTest:

NSIndexSet *indexSet = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    MyObject *myObject = (MyObject *)obj;
    return [myObject.firstName isEqualToString:@"Bob"];
}];

This returns an index set of all the objects in the array with the first name of "Bob".

Upvotes: 7

bobnoble
bobnoble

Reputation: 5824

Another approach returning a new array containing only matching objects:

-(NSArray *)matchingClientsFromArray:(NSArray *)objects withFirstName:(NSString *)firstName andLastName:(NSString *)lastName{
    NSMutableArray *objectArray = [NSMutableArray new];
    for (Client *client in objectArray){
        if ([client.firstName isEqualToString:firstName] &&
              [client.lastName isEqualToString:lastName]) {
            [objectArray addObject:client];
        }
    }
    return [objectArray copy];
}

Upvotes: 0

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

As a second thought, I think -filteredArrayUsingPredicate: might be better for you.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@", @"firstName", @"Bob"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];

This returns a sub-array of objects from the array that have the first name of "Bob".

Upvotes: 11

Related Questions