0

可以很好地计算诸如 max、min 和 avg 之类的东西,

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"]);
]

但是,鉴于我有“项目”实体,我购买它的价格和我出售它的价格作为属性,我如何使用 NSExpressions 计算所有项目实体的总利润?

谢谢

4

1 回答 1

1

以下表达式描述计算每个对象的价格差异:

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);

编辑:(在我写上面的答案时,这个问题被编辑了。)计算所有价格差异的总和似乎是不可能用一个单一的获取请求,例如链式表达式来执行 Core Data 中的计算。但是您可以使用上面的表达式描述获取所有价格差异的数组,并使用 Key-Value 编码计算总和:

NSArray *profits = result of fetch request
NSNumber *totalProfit = [profits valueForKeyPath:@"@sum.profit"];
NSLog(@"%@", totalProfit);
于 2013-07-11T15:11:27.910 回答