首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NSExpressions对两个核心数据属性执行操作

问使用NSExpressions对两个核心数据属性执行操作
EN

Stack Overflow用户
提问于 2013-07-11 22:21:04
回答 1查看 2K关注 0票数 0

像max、min和avg这样的东西可以很好地计算出来,

代码语言:javascript
复制
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实体的总利润?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-11 23:11:28

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

代码语言:javascript
复制
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。但是您可以使用上面的表达式描述来获取所有差价的数组,并使用键值编码计算总和:

代码语言:javascript
复制
NSArray *profits = result of fetch request
NSNumber *totalProfit = [profits valueForKeyPath:@"@sum.profit"];
NSLog(@"%@", totalProfit);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17595929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档