Filter array in ios checking multiple properties

旧街凉风 提交于 2019-12-05 23:36:09

问题


I have an array of custom objects. The custom object look like this

@interface User : NSObject
@property(nonatomic, strong)NSString *user_Id;
@property(nonatomic, strong)NSString *user_Name;
@property(nonatomic, strong)NSString *user_UserName;
@end

I have to filter the array checking 2 properties.That is if I search a then it should get list of users filtered from array contains a in user_Name or user_Id .How can i achieve this? For a single property i know[user_Name]

NSString *predicateString = @"user_Name MATCHES[c] %@";
NSString *matchString =  [NSString stringWithFormat: @".*%@.*",searchText];
NSPredicate *predicate =[NSPredicate predicateWithFormat:predicateString, matchString];
self.searchResults = [userArray filteredArrayUsingPredicate:predicate];

回答1:


You can join predicate conditions with OR, such as:

NSString *predicateString = @"(user_Name MATCHES[c] %@) OR (user_Id MATCHES[c] %@)";

Alternately, you could filter the array by using indexesOfObjectsPassingTest: with an appropriate test block and then objectsAtIndexes: to get an array of the objects passing the test.




回答2:


NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(user_Name== %@) || (user_Id== %@), <name>,  <id>];



回答3:


Try to use this predicate string

NSString *predicateString = @"user_Name MATCHES[c] %@ OR user_Id MATCHES[c] %@";


来源:https://stackoverflow.com/questions/15583195/filter-array-in-ios-checking-multiple-properties

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