Monday 1 September 2014

Predicates and compound predicate to filter data

Hi friends in normal iphone application in all applications we see search feature normally.
Search can be done from server side as well as from application side locally.

we can search data locally using NSPredicate and NSCompoundPredicate .

I have one NSMutableArray which i created this way:

NSMutableArray *arrAllData = [NSMutableArray array];
[arrAllData addObject :@{@"id":@"1",@"title":@"Mittal",@"search_type":@"Sr Enginner",}];
[arrAllData addObject :@{@"id":@"2",@"title":@"Rupal",@"search_type":@"Jr Enginner",}];
[arrAllData addObject :@{@"id":@"3",@"title":@"Sunny",@"search_type":@"QA",}];
[arrAllData addObject :@{@"id":@"3",@"title":@"Adithi",@"search_type":@"Director",}];
[arrAllData addObject :@{@"id":@"3",@"title":@"Nirman",@"search_type":@"Director",}];


Now we want to filter the data according to Boss and Employee:
Please apply this code.

NSMutableArray *predicates = [NSMutableArray array];
NSString *filter = @"search_type == %@";
NSPredicate *commonPred = [NSPredicate predicateWithFormat:filter, @"Sr Enginner"];
[predicates addObject:commonPred];
NSPredicate *jrEngineerPred = [NSPredicate predicateWithFormat:filter, @"Jr Enginner"];
[predicates addObject: jrEngineerPred];
NSPredicate *QAPred = [NSPredicate predicateWithFormat:filter, @"QA"];
[predicates addObject:QA];
NSPredicate *resultPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];
NSArray *arr_Data = [arrAllData filteredArrayUsingPredicate:resultPredicate];
 NSMutableArray *arSearchEmployeeData = [arr_Data mutableCopy];


arr_Data =  [NSMutableArray alloc]init];
commonPred = [NSPredicate predicateWithFormat:filter, @"Director"];
arr_Data = [arrAllData filteredArrayUsingPredicate:
                              commonPred];
 NSMutableArray *arSearcBossData = [arr_Data mutableCopy];

Happy Coding!!

Thanks.