user1590031
user1590031

Reputation: 308

Filter NSArray with NSPredicate

I want to filter an array of User objects (User has fullname, user_id and some more attributes..) according to firstName or lastName that begin with some string.
I know how to filter according to one condition:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH[cd] %@", word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];  

this will give me all the users that has a firstName that starts with "word".
But what if I want all the users that has a firstName or lastName that start with "word"?

Upvotes: 2

Views: 1349

Answers (2)

Paresh Navadiya
Paresh Navadiya

Reputation: 38259

Use like this:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH %@ OR lastName BEGINSWITH %@", word, word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];

Upvotes: 2

Fogmeister
Fogmeister

Reputation: 77661

You can use the class NSCompoundPredicate to create compound predicates.

NSPredicate *firstNamePred = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH[cd] %@", word];
NSPredicate *lastNamePred = [NSPredicate predicateWithFormat:@"lastName BEGINSWITH[cd] %@", word];

NSArray *predicates = @[firstNamePred, lastNamePred];

NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];

NSArray* resArr = [myArray filteredArrayUsingPredicate:compoundPredicate];

this is one way that I like doing.

Or you can do ...

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH[cd] %@ OR lastName BEGINSWITH[cd] %@", word, word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];

either will work.

Upvotes: 6

Related Questions