I
I
iMike2014-08-18 19:17:09
iOS
iMike, 2014-08-18 19:17:09

How to multiply two columns and get sum of multiplications from all columns in CoreData?

I store in a table a list of products with their price and quantity.
I need to calculate the amount (quantity * price) from the list of goods for each product
and get the total amount of all goods.
In mySQL it would look something like this: SELECT SUM(price * quantity) FROM documentGoods
Here is my code for CoreData, but it doesn't work.

NSFetchRequest *fetch = ;
[fetch setResultType:NSDictionaryResultType];

NSExpression *multiplyExpression = [NSExpression expressionForFunction:@"multiply:by:" arguments:@];
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 someone help me?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question