像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"]);
]但是,如果我有" Item“实体,以我购买它的价格和卖出它的价格作为属性,我如何使用NSExpressions计算所有Item实体的总利润?
谢谢
发布于 2013-07-11 23:11:28
下面的表达式描述计算每个对象的差价:
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);编辑:(这个问题是在我写上面答案的时候编辑的。)对于单个fetch请求,计算所有价格差异的总和似乎是不可能的,例如,请参阅Chained expressions to perform calculations in Core Data。但是您可以使用上面的表达式描述来获取所有差价的数组,并使用键值编码计算总和:
NSArray *profits = result of fetch request
NSNumber *totalProfit = [profits valueForKeyPath:@"@sum.profit"];
NSLog(@"%@", totalProfit);https://stackoverflow.com/questions/17595929
复制相似问题