是否有可能使用表达式作为参数的sum:
体现在哪里?
我有实体( NSManagedObject
类) Drink
与性能costPerDrink
, numberOfDrinks
和drinkingDate
。
我想获得总成本(总和numberOfDrinks
乘以costPerDrink
时间内)。 虽然我没有问题得到对单个属性总和(以下EG和numberOfDrinks
时间内),当我尝试对我有错误另一个(乘)表达式中使用和表达:
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:
体现在哪里?