是否可以将表达式用作sum:
表达式的参数?
我的实体(NSManagedObject
类)Drink
包含属性costPerDrink
,numberOfDrinks
和drinkingDate
。
我希望在一段时间内得到总费用(numberOfDrinks
乘以costPerDrink
)的总和。虽然我在单个属性上获得总和没有问题(例如,在时间段内numberOfDrinks
的总和),但当我尝试在另一个(乘法)表达式上使用sum表达式时,我得到了错误:
NSInvalidArgumentException, reason: Unsupported argument to sum :
(
"costPerDrink * numberOfDrinks"
)
参见代码:
// Init fech
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Drink" inManagedObjectContext:[Service appContext]];
[request setEntity:entity];
// Return dictionary
[request setResultType:NSDictionaryResultType];
// Set conditions
[request setPredicate:[NSPredicate predicateWithFormat:@"(drinkingDate>=%@) AND (drinkingDate<=%@)", self.startDate, self.endDate]];
// Set 1st column to be returned - count of drinks
NSExpression *drinksExpression = [NSExpression expressionForKeyPath:@"numberOfDrinks"];
NSExpression *sumDrinksExpression = [NSExpression expressionForFunction:@"sum:" arguments:[NSArray arrayWithObject:drinksExpression]];
NSExpressionDescription *sumDrinksResultDescription = [[NSExpressionDescription alloc] init];
[sumDrinksResultDescription setName:@"sumDrinks"];
[sumDrinksResultDescription setExpression:sumDrinksExpression];
[sumDrinksResultDescription setExpressionResultType:NSInteger32AttributeType];
// Set 2nd column to be returned - total cost
NSExpression *costExpression = [NSExpression expressionForKeyPath:@"costPerDrink"];
NSExpression *totalExpression = [NSExpression expressionForFunction:@"multiply:by:"
arguments:[NSArray arrayWithObjects:costExpression,
drinksExpression, nil]];
NSExpression *sumCostExpression = [NSExpression expressionForFunction:@"sum:" arguments:[NSArray arrayWithObject:totalExpression]];
NSExpressionDescription *sumCostResultDescription = [[NSExpressionDescription alloc] init];
[sumCostResultDescription setName:@"sumCost"];
[sumCostResultDescription setExpression:sumCostExpression];
[sumCostResultDescription setExpressionResultType:NSDecimalAttributeType];
// Add expressions to fetch
[request setPropertiesToFetch:[NSArray arrayWithObjects: sumDrinksResultDescription, sumCostResultDescription, nil]];
// Execute fech
NSError *error;
NSArray *result = [[Service appContext] executeFetchRequest:request error:&error];
我完全理解,可以通过向totalCost
实体添加自动计算的Drink
属性,然后在没有sum:
表达式的提取中使用multiply:by:
来解决特定问题,但问题仍然存在 - 是否可以将表达式用作sum:
表达式的参数?