How to create a predicate that compares all properties of an object?

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

If I want to search for the string "john" in all 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"];

+7
ios key-value-coding nspredicate
source share
2 answers

"everything contains" does not work in the predicate, and (as far as I know) there is no similar syntax for obtaining the desired result.

The following code creates a “compound predicate” of 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" 
+4
source share

You can do it this way

 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 this is a fix. :( not for dynamic :)

0
source share

All Articles