I have a goods in document and I want to multiply quantity and price of every good in document and sum it.
In mySQL something like this: SELECT SUM(price * quantity) FROM documentGoods
Here is my code, but it doesn't work.
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:self.tableName inManagedObjectContext:moc]];
[fetch setResultType:NSDictionaryResultType];
NSExpression *multiplyExpression = [NSExpression expressionForFunction:@"multiply:by:" arguments:@[[NSExpression expressionForKeyPath:@"quantity"], [NSExpression expressionForKeyPath:@"price"]]];
NSExpressionDescription *expressionMultipliedDescription = [[NSExpressionDescription alloc] init];
[expressionMultipliedDescription setName:@"multiplied"];
[expressionMultipliedDescription setExpression:multiplyExpression];
[expressionMultipliedDescription setExpressionResultType:NSDecimalAttributeType];
NSExpression *sumExpression = [NSExpression expressionForFunction:@"sum:" arguments:@[[NSExpression expressionForKeyPath:@"multiplied"]]];
NSExpressionDescription *expressionSummaryDescription = [[NSExpressionDescription alloc] init];
[expressionSummaryDescription setName:@"summary"];
[expressionSummaryDescription setExpression:sumExpression];
[expressionSummaryDescription setExpressionResultType:NSDecimalAttributeType];
[fetch setPropertiesToFetch:@[expressionSummaryDescription]];
NSPredicate *searchFilter = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"removed = NO"]]];
[fetch setPredicate:searchFilter];
NSError *error = nil;
NSArray *objects = [moc executeFetchRequest:fetch error:&error];
if(objects && [objects count] > 0)
return [[objects objectAtIndex:0] valueForKey:@"summary"];
return [[NSDecimalNumber alloc] initWithFloat:.0f];
Can anyone please help me?
I faced a similar scenario where my entity is "Cart" and has fields price and quantity. To get sum(quantity * price) from cart i used the following code. The last NSLog would log the required total cart price