AAV
AAV

Reputation: 3803

Search NSArray using NSPredicate

I am new to NSPredicate so sorry if I am asking stupid question. I have two NSArray (keyArray and valueArray). I have to find match in valueArray using keyArray. Below code is working fine but I have to search one by one. Any way to search an array using a different key array.

        NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"companyId = %@", [[[self selectedCompanies] objectAtIndex:0] companiesIdentifier]];
    NSLog(@"Users: %@", [[[self userData] users] filteredArrayUsingPredicate:userPredicate]);

    NSPredicate *userPredicate1 = [NSPredicate predicateWithFormat:@"companyId = %@", [[[self selectedCompanies] objectAtIndex:1] companiesIdentifier]];
    NSLog(@"Users: %@", [[[self userData] users] filteredArrayUsingPredicate:userPredicate1]);

Upvotes: 0

Views: 105

Answers (1)

Léo Natan
Léo Natan

Reputation: 57040

You can do:

NSPredicate *userPredicate1 = [NSPredicate predicateWithFormat:@"companyId IN %@", [[self selectedCompanies] valueForKey:@"companiesIdentifier"];
NSLog(@"Users: %@", [[[self userData] users] filteredArrayUsingPredicate:userPredicate1]);

What happens here is we take the companiesIdentifier of all selected companies and match users based on those identifiers.

valueForKey: on an array object returns an array with the value of the required key for each object in the array. IN is a predicate operator searching in a collection (array, set, etc.).

Upvotes: 1

Related Questions