2

我想根据或以某个字符串开头的User对象数组( Userhasfullnameuser_id更多属性..)过滤。 我知道如何根据一种条件进行过滤: firstNamelastName

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

这将为我提供所有名字以“word”开头的用户。
但是,如果我想要所有名字或姓氏都以“word”开头的用户怎么办?

4

2 回答 2

6

您可以使用该类NSCompoundPredicate来创建复合谓词。

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];

这是我喜欢做的一种方式。

或者你可以做...

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

要么会工作。

于 2012-10-10T10:41:06.973 回答
2

像这样使用:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH %@ OR lastName BEGINSWITH %@", word, word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];
于 2012-10-10T10:43:29.423 回答