Filter NSArray with NSPredicate

2019-07-10 07:17发布

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"?

2条回答
相关推荐>>
2楼-- · 2019-07-10 07:58

Use like this:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH %@ OR lastName BEGINSWITH %@", word, word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];
查看更多
Animai°情兽
3楼-- · 2019-07-10 08:18

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.

查看更多
登录 后发表回答