Filter in ios checking multiple properties

I have an array of custom objects. A custom object looks 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 need to filter an array checking 2 properties. That is, if I search for a , then it should get a list of users filtered from the array containing a in user_Name or user_Id . How can I achieve this? For one 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]; 
+7
source share
3 answers

You can join predicate conditions with OR , for example:

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

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

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

Try using this predicate string

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

All Articles