Filter NSArray with NSPredicate

笑着哭i 提交于 2019-12-24 01:17:01

问题


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


回答1:


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.




回答2:


Use like this:

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


来源:https://stackoverflow.com/questions/12817340/filter-nsarray-with-nspredicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!