使用NSPredicate过滤NSArray

use*_*031 2 iphone objective-c nsarray nspredicate ios

我想根据或以某些字符串开头过滤一个User对象数组(Userfullname,user_id以及一些更多属性..). 我知道如何根据一个条件过滤: firstNamelastName

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH[cd] %@", word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];  
Run Code Online (Sandbox Code Playgroud)

这将为我提供具有以"word"开头的firstName的所有用户.
但是如果我希望所有拥有firstName或lastName以"word"开头的用户怎么办?

Fog*_*ter 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];
Run Code Online (Sandbox Code Playgroud)

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

或者你可以......

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"firstName BEGINSWITH[cd] %@ OR lastName BEGINSWITH[cd] %@", word, word];
NSArray* resArr = [myArray filteredArrayUsingPredicate:predicate];
Run Code Online (Sandbox Code Playgroud)

要么会奏效.