Search code examples
ioscore-datanspredicatensfetchrequest

NSPredicate from Core Data selecting by Object ID (and potentially summing)


I'm finding my way to the advanced part of core data. I know it is not SQL, and there are limitations, however, how would I translate the code below to a NSPredicate to be applied in a fetch request?

Product* p = self.product; //this is a managed object
double vol=0;
for (PlanningItem* pi in self.planitems) {
 if (pi.product==p)
    vol+=pi.volume;
  1. I want to fetch all plan items that have p as their product.
  2. Next I want to sum all the volumes of that set.

How do I do 1 in a fetch request with a NSPredicate? Can i do 2 at the same time?

I'm asking for the string for the NSPredicate. I am capable of building the Fetchrequest myself.

Tx!


Solution

  • // Create the predicate
    NSPredicate *productPredicate = 
        [NSPredicate predicateWithFormat:@"(product == %@)", product];
    
    // Apply the predicate to your FetchRequest
    [fetchRequest setPredicate:productPredicate];