How to use @sum with CoreData

I have a model of the week that has Day as children. The week properties use the "days" relationship property to access all related Day objects. The daily model has a duration property.

How can I determine the sum of the length of the day for the specified object of the week? It would be great to have a code example on how to create a predicate object with the @sum function.

Is it also possible to have a “computed” weekDuration property in the Week class that sets the value of the sum of the associated long days during the extraction? This would be the most elegant solution to these problems, but I do not think this is possible with CoreData.

+5
source share
1 answer

Here is an example of how you set up your search query for only weeks when the sum of the days is more than 100.

NSManagedObjectContext *context = ...;
NSManagedObjectModel *model = ...;
NSFetchRequest *fr = [[NSFetchRequest alloc] init];
fr.entity = [model.entitiesByName objectForKey:@"Week"];

//This predicate will be compiled into pure SQL
fr.predicate = [NSPredicate predicateWithFormat:@"days.@sum.duration > 100"];

NSError *error = nil;
NSArray *results = [context executeFetchRequest:fr error:&error];
if (error) {
  NSLog(@"ERROR: %@", error);
}
NSLog(@"Results: %@", results);

In fact, you can implement the computed property in the same way, just add it to a subclass of NSManagedObject that supports the Week object:

- (NSNumber *) duration {
  return [self valueForKeyPath:@"days.@sum.duration"];
}
+8
source

All Articles