【问题标题】:Perform operation on two Core Data Attributes with NSExpressions使用 NSExpressions 对两个核心数据属性执行操作
【发布时间】:2013-07-11 14:21:03
【问题描述】:

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 计算所有项目实体的总利润?

谢谢

【问题讨论】:

    标签: objective-c core-data nsexpression


    【解决方案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);
    

    编辑:(在我编写上述答案时,该问题已被编辑。)计算所有价格差异的 sum 似乎无法通过单个 fetch 请求, 参见例如Chained expressions to perform calculations in Core Data。但是你可以获取所有价格差异的数组,使用 上面的表达式描述,并使用Key-Value编码计算总和:

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

    【讨论】:

    • 嗯,我使用上面的表达式描述收到此崩溃错误消息:由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无效的键路径(对仅 toOne 键路径的聚合操作的请求):purchasePrice '
    • @Skyler:我现在已经对此进行了测试,它对我有用。我已将完整的获取代码添加到答案中。
    • @Skyler:也许您可以显示您的实体的定义和您当前的代码。
    • 事实证明问题是为方法 NSFetchRequest setPropertiesToFetch: 传递了一个大小大于 1 的数组。我试图执行多项操作,例如对所有购买价格求和、对所有销售价格求和等。如果我将获取请求的属性拆分为获取,应用程序不会崩溃。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多