Reputation: 308
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
Reputation: 38259
Use like this:
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH %@ OR lastName BEGINSWITH %@", word, word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];
Upvotes: 2
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