7

For example, I have an object that has three properties: firstName, middleName, lastName.

If I want to search a string "john" in all the properties using NSPredicate.

Instead of creating a predicate like:

[NSPredicate predicateWithFormat:@"(firstName contains[cd] %@) OR (lastName contains[cd] %@) OR (middleName contains[cd] %@)", @"john", @"john", @"john"];

Can I do something like:

[NSPredicate predicateWithFormat:@"(all contains[cd] %@), @"john"];

David Liu
  • 16,374
  • 12
  • 37
  • 38

2 Answers2

4

"all contains" does not work in a predicate, and (as far as I know) there is no similar syntax to get the desired result.

The following code creates a "compound predicate" from all "String" attributes in the entity:

NSString *searchText = @"john";
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:context];
NSMutableArray *subPredicates = [NSMutableArray array];
for (NSAttributeDescription *attr in [entity properties]) {
    if ([attr isKindOfClass:[NSAttributeDescription class]]) {
        if ([attr attributeType] == NSStringAttributeType) {
            NSPredicate *tmp = [NSPredicate predicateWithFormat:@"%K CONTAINS[cd] %@", [attr name], searchText];
            [subPredicates addObject:tmp];
        }
    }
}
NSPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];

NSLog(@"%@", predicate);
// firstName CONTAINS[cd] "john" OR lastName CONTAINS[cd] "john" OR middleName CONTAINS[cd] "john"
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • in case you've simple nsobject then you can use property enumerator to get names of all properties http://tny.cz/e4974e2b – Abid Hussain Apr 21 '14 at 14:27
  • 2
    @AbidHussain: Yes, but enumerating the properties would give also all properties that are inherited from NSManagedObject or NSObject. This method gives only the attributes defined for the entity. – Martin R Apr 21 '14 at 14:29
0

You can do it in such way like,

NSMutableArray *allTheContaint = [[NSMutableArray alloc] init];
[allTheContaint addObject:allTheContaint.firstName];
[allTheContaint addObject:allTheContaint.middleName];
[allTheContaint addObject:allTheContaint.lastName];

NSPredicate *predicateProduct = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", @"john"];
NSArray *filteredArray = [self.listOfProducts filteredArrayUsingPredicate:predicateProduct];
NSLog(@"%@", filteredArray);

But it is fix. :( not for dynamic :)

iPatel
  • 46,010
  • 16
  • 115
  • 137