使用另一种表达作为参数总结从NSManagedObject获取聚合数据:表达(Fetch aggre

2019-07-05 07:06发布

是否有可能使用表达式作为参数的sum:体现在哪里?

我有实体( NSManagedObject类) Drink与性能costPerDrinknumberOfDrinksdrinkingDate

我想获得总成本(总和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:体现在哪里?

文章来源: Fetch aggregate data from NSManagedObject using another expression as argument to sum: expression