如何乘以两列,并在CoreData中求和?

我在文件中有一个货物,我想把文件中每个货物的数量和价格乘以总和。

在mySQL像这样: SELECT SUM(price * quantity) FROM documentGoods

这是我的代码,但它不起作用。

 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]; 

谁能帮帮我吗?

我面临一个类似的情况,我的实体是“购物车”,并且具有字段价格和数量。 为了从购物车得到总和(数量*价格),我使用了下面的代码。 最后一个NSLog将logging所需的总购物车价格

 NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.entity = [NSEntityDescription entityForName:@"Cart" inManagedObjectContext:self.managedObjectContext]; request.resultType = NSDictionaryResultType; NSExpressionDescription *productTotalDescr = [[NSExpressionDescription alloc] init]; [productTotalDescr setName:@"productTotal"]; [productTotalDescr setExpression:[NSExpression expressionForFunction:@"multiply:by:" arguments:[NSArray arrayWithObjects: [NSExpression expressionForKeyPath:@"price"], [NSExpression expressionForKeyPath:@"quantity"], nil]]]; [productTotalDescr setExpressionResultType:NSInteger64AttributeType]; request.propertiesToFetch = [NSArray arrayWithObjects:productTotalDescr, nil]; NSError *err = nil; NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&err]; NSLog(@"%@",[results valueForKeyPath:@"productTotal"]);