3

是否可以使用表达式作为表达式的参数sum:

我有具有属性的实体(NSManagedObject类)和.DrinkcostPerDrinknumberOfDrinksdrinkingDate

我想在一段时间内获得总成本的总和(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:在没有表达式的情况下使用 in fetch来解决特定问题,multiply:by:但问题仍然存在 - 是否可以使用表达式作为表达式的参数sum:

4

0 回答 0