Yoav Schwartz
Yoav Schwartz

Reputation: 2027

Using NSFetchRequest with complex NSPredicate in a NSFetchRequestController

Im trying to implement something that I'm sure have been implemented a million times before, a search in the core data database, displayed in a table using a fetchRequestController and the searchController.

My problem is writing the NSPredicate for the NSFetchRequest. According to the NSPredicate guide by Apple, not everything you can do in Sqlite is possible with core data. I have been trying to find a solution for some time, but maybe one of you can use his experience to help me.

CoreData DB description: Shops has a MANY TO MANY relationship with DiscountProgam.

My use case is as follows: I need to filter out Shops who's name/address/zip/city contains the search string. that's the easy part. The hard part is creating the section of the database I want to filter from, because I have an array of "active" discountPrograms UID's, and I only want shops that have one of the active discount programs in their "discountPrograms" set. So in pseudo code that would be:

FROM Shops who have at least one discountProgram who's uid IN activeDiscountProgramsArray WHERE name/address/zip/city CONTAINS searchString

Is this possible? am I over reaching the limits of predicates? If so, how could I do it differently?

Upvotes: 2

Views: 413

Answers (1)

Wain
Wain

Reputation: 119031

Yes, NSPredicate can analyse both the direct attributes of the target entity of a fetch and the attributes of its relationships. Try:

NSArray *validUIDs = ...;
NSString *searchTerm = ...;

[NSPredicate predicateWithFormat:@"(name CONTAINS[cd] %@ OR zip CONTAINS[cd] %@) AND (SUBQUERY(discountProgram, $d, $d.UID IN %@).@count > 0)", searchTerm, searchTerm, validUIDs];

Upvotes: 1

Related Questions