NSPredicate for plural relationships in many Core Data

I have an NSPredicate that includes several aggregate filters that throw an exception.

I have the following kernel data model:

Master Data Model

I want to select those ApparelItems for which any of the colours has rgb 13576743 and for which all picks have pickTime earlier than the specified NSDate .

My code for creating a predicate:

 let request = NSFetchRequest(entityName: "ApparelItem") var predicates = [NSPredicate]() predicates.append(NSPredicate(format: "ANY colours.rgb = 13576743")) // find the NSDate representing midnight x days ago let cal = NSCalendar.currentCalendar() if let xDaysAgo = cal.dateByAddingUnit(.Day, value: -2, toDate: NSDate(), options: []) { let midnightXDaysAgo = cal.startOfDayForDate(xDaysAgo) predicates.append(NSPredicate(format: "(ALL picks.pickTime < %@)", midnightXDaysAgo)) } request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates) let searchData = try? objectContext.executeFetchRequest(request) 

I get the following exception:

 Exception name=NSInvalidArgumentException, reason=Unsupported predicate (ANY colours.rgb == 13576743) AND ALL picks.pickTime < CAST(479347200.000000, "NSDate") 

I tried:

  • Each individual predicate works fine. Those. ANY colours.rgb = ... works, ALL picks.pickTime < ... also works. They simply do not work when combined into the same query.

  • Combining the two uses in a single query associated with AND , instead of using NSCompoundPredicate . The result is the same.

Is it possible that master data simply does not support filtering relationships of more than one? That would seem odd. In which case should I do it higher?

+6
source share
2 answers

You can probably try SUBQUERY() for NSPredicate .

In the code below, I got out of some hunch and am not very sure if it works or not. This usually requires a lot of trial and error to offer a to-many request with NSPredicate .

 var predicates = [NSPredicate]() predicates.append(NSPredicate(format: "SUBQUERY(colours, $colour, ANY $colour.rgb = 13576743) .@count > 0")) let cal = NSCalendar.currentCalendar() if let xDaysAgo = cal.dateByAddingUnit(.Day, value: -2, toDate: NSDate(), options: []) { let midnightXDaysAgo = cal.startOfDayForDate(xDaysAgo) predicates.append(NSPredicate(format: "SUBQUERY(picks, $pick, ALL $pick.pickTime < %@) .@count > 0", midnightXDaysAgo)) } 
+2
source

Colors and highlights are two different objects, so you can filter them without using SUBQUERY . One predicate or complex predicate should be in order.

From the error message, it seems that something is wrong with the date. Verify that you have the expected data type in the subclasses of the managed entity. If you used "primitive values" when creating subclasses, you would need NSTimeInterval , not NSDate .

0
source

All Articles