使用NSPredicate过滤NSArray [英] Filter NSArray with NSPredicate
问题描述
我想过滤 User
对象的数组( User
具有 fullname
, user_id
和其他一些属性..)根据以某些字符串开头的 firstName
或 lastName
.
我知道如何根据一种条件进行过滤:
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];
这将给我所有具有以"word"开头的名字的用户.
但是,如果我希望所有具有以"word"开头的名字或姓氏的用户呢?
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"?
推荐答案
您可以使用类 NSCompoundPredicate
创建复合谓词.
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.
或者你可以做...
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH[cd] %@ OR lastName BEGINSWITH[cd] %@", word, word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];
两者都将起作用.
这篇关于使用NSPredicate过滤NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!