How do I translate SQL:
select sum( field1 * field2 ) from table where field3 = 8
to equivalent CoreData NSPredicate code, please? Is it possible without fetching everything and running an ugly for loop?
How do I translate SQL:
select sum( field1 * field2 ) from table where field3 = 8
to equivalent CoreData NSPredicate code, please? Is it possible without fetching everything and running an ugly for loop?
Why does it need to be performed in the SQL?
If you are using an NSManagedObject
sub class then you can just create a virtual property that will do that calculation. (Ignore the naming I do not know you domain)
MyClass.h
@property (nonatomic, readonly) CGFloat sumOfField1AndField2;
MyClass.m
- (CGFloat)sumOfField1AndField2;
{
return self.field1 * self.field2;
}
Your entity should have a fetched property calculated property that multiplies the two fields. The solution to your query is to combine NSPredicate
and key-value-coding:
fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"table"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"field3 = %@", @8];
NSArray *results = [self.managedObjectContext
executeFetchRequest:fetchRequest error:nil];
NSNumber *sum = [results valueForKeyPath:@"@sum.fetchedProperty"];
As you pointed out, it is really not a fetched property but a calculated field. I made a test along these lines:
// NSManagedObjectSubclass .h
@property (nonatomic, strong) NSNumber *product;
// .m
@dynamic product;
-(NSNumber *)product {
return @(value1.floatValue * value2.floatValue);
}
and this worked:
NSLog(@"Sum of products: %@", [fetchedObjects valueForKeyPath:@"@sum.product"];