Sometimes we might need to filter a list of records. For instance : We have an array of employees and we want to get all employees who live in the city Dehradun.
Here is the structure of Employee class :
@interface Employee : NSObject
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *city;
@property (nonatomic,assign) float salary;
@end
Now to filter array of employee objects we can do the following using NSPredicate :
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city=%@",@"Dehradun"];
NSArray *filteredArray = [empArr filteredArrayUsingPredicate:predicate];
For a case insensitive filter we can use [c] like this :
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city=[c]%@",@"dehradun"];
We can also combine conditions. Like if we want to get employees with name 'John' or city 'Dehradun' we can do :
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(city=%@)||(name=%@)",@"Dehradun",@"John"];
For AND condition we need to use &&
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(city=%@)&&(name=%@)",@"Dehradun",@"John"];
The left hand key path can also be substituted using %K.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K=[c]%@",@"city",@"dehradun"];
Basic comparision operators
=, == (equal) >=,=> (greaterthanorequal) <=, =< (lessthanorequal) > (greaterthan) < (lessthan) !=, <> (notequal)
BETWEEN operator
Used for values lying within a range
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"salary BETWEEN %@",@[@1200,@20000]];
String Comparisons
BEGINSWITH, CONTAINS, ENDSWITH, LIKE, MATCHES
With LIKE operator we can use * for unknown number of characters and ? for a single unknown character.
Following predicate will get all employees with city name ending with 'dun'
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city LIKE %@",@"*dun"];
Following predicate will get all employees with city name begining with 'Dehra' and having 3 more characters in the end.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city LIKE %@",@"Dehra???"];
Predicates also work for array of nsdictionaries.
All of above mentioned and other comparisons can be seen in detail in Apple documentation here
0 Comment(s)