- Use
p1 = [NSCompoundPredicate orPredicateWithSubpredicates:...]
to create a predicate that filters the county (similar to what you already did, but only with the values fromcountryFilters
. - Use
p2 = [NSCompoundPredicate orPredicateWithSubpredicates:...]
to create another predicate that filters the place (now with the values fromplaceFilters
). - Use
filter = [NSCompoundPredicate andPredicateWithSubpredicates:@[p1, p2]]
to create the final predicate from the previous two predicates.
NSPredicate with subpredicates
-
17-07-2023 - |
Question
I have a Core Data object which contains some properties. 2 of those properties are:
- Country
- Place
What I want to achieve is that the user can select the countries which he wants to see, and also have the option to filter those countries on some places.
For instance:
The user wants to view only the objects from "USA" which have the place "New York" or "Chicago".
I've tried to do this with the following code:
NSMutableArray *subpredicates = [NSMutableArray array];
for (NSString *key in countryFilters) {
NSPredicate *subpredicate = [NSPredicate predicateWithFormat:@"country contains[cd] %@", key];
[subpredicates addObject:subpredicate];
}
for (NSString *key in placeFilters) {
NSPredicate *subpredicate = [NSPredicate predicateWithFormat:@"place contains[cd] %@", key];
[subpredicates addObject:subpredicate];
}
NSPredicate *filter = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
[self.fetchedResultsController.fetchRequest setPredicate:filter];
This works, but I also see objects which have a place with the same name but in another country... This is correct ofcourse, but I want to know how I can nest some NSPredicates (In this case: all or some countries, and from that result, only the ones with a specific place)
(Above is an example, my real objects contain other properties but the idea is the same. The only problem is that I cannot post the real object structure here for security purposes...)
Hope anyone can help..
Thanks in advance!
Solution