Objective c 使用N表达式对两个核心数据属性执行操作

Objective c 使用N表达式对两个核心数据属性执行操作,objective-c,core-data,nsexpression,Objective C,Core Data,Nsexpression,最大值、最小值和平均值都可以很好地计算 NSExpression *maxDate = [NSExpression expressionForKeyPath:@"startDate"]; NSExpression *maxDateExpression = [NSExpression expressionForFunction:@"max:" arguments:@[maxDat

最大值、最小值和平均值都可以很好地计算

NSExpression *maxDate = [NSExpression expressionForKeyPath:@"startDate"];
NSExpression *maxDateExpression = [NSExpression expressionForFunction:@"max:"
                                                            arguments:@[maxDate]];
NSExpressionDescription *maxDateExpressionDescription = [[NSExpressionDescription alloc] init];
[maxDateExpressionDescription setName:@"maxDate"];
[maxDateExpressionDescription setExpression:maxDateExpression];
[maxDateExpressionDescription setExpressionResultType:NSDateAttributeType];



[request setPropertiesToFetch:@[maxDateExpressionDescription]];


// Execute the fetch.
NSError *error = nil;

NSArray *objects = [context executeFetchRequest:request error:&error];
if (error) {
    // Handle the error.

    NSLog(@"Error!");
}
else {
    NSLog(@"Max date is: %@", [objects[0] objectForKey:@"maxDate"]);
]
但是,考虑到我有“项目”实体,以购买价格和出售价格作为属性,我如何使用N表达式计算所有项目实体的总利润


谢谢

以下表达式说明计算每个对象的价差:

NSExpression *price1Expr = [NSExpression expressionForKeyPath:@"price1"];
NSExpression *price2Expr = [NSExpression expressionForKeyPath:@"price2"];
NSExpression *profitExpr = [NSExpression
                                    expressionForFunction:@"from:subtract:"
                                    arguments:@[price2Expr, price1Expr]];

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"profit"];
[expressionDescription setExpression:profitExpr];
[expressionDescription setExpressionResultType:NSDoubleAttributeType];

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
[request setPropertiesToFetch:@[expressionDescription]];
[request setResultType:NSDictionaryResultType];
NSArray *profits = [context executeFetchRequest:request error:&error];
NSLog(@"%@", profits);
编辑:(这个问题是在我写上述答案时编辑的。)计算所有价格差异的总和似乎不可能只通过一个获取请求, 例如,见。但是您可以使用 上述表达式描述,并使用键值编码计算总和:

NSArray *profits = result of fetch request
NSNumber *totalProfit = [profits valueForKeyPath:@"@sum.profit"];
NSLog(@"%@", totalProfit);

Hmmm我使用上面的表达式得到这个崩溃错误消息描述:由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无效的密钥路径(请求仅对toOne密钥路径进行聚合操作):purchasePrice'@Skyler:我现在已经测试过了,它对我有效。我已将完整的获取代码添加到答案中。@Skyler:也许您可以显示实体的定义和当前代码。结果表明,问题是传递了一个大于1的数组,用于方法NSFetchRequest setPropertiesToFetch:。我试图执行多个操作,例如合计所有购买价格、合计所有销售价格等。如果我将提取请求的属性拆分为提取,则应用程序不会崩溃。谢谢你的帮助。