如何对计算所得的属性求和? [英] How to sum on a calculated property?

查看:116
本文介绍了如何对计算所得的属性求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定尝试将SQL逻辑应用于Core Data感到内,但是即使在阅读了Apple文档之后,我仍然不确定正确的方法。

I'm sure I'm guilty of trying to apply SQL logic to Core Data, but even after reading the Apple docs I'm still not sure of the correct approach.

汇总核心数据实体中两个日期属性之差的最佳策略是什么?我在 appt类上有一个 numHours计算属性,但在xcdatamodel中却没有。下面的代码失败,并显示在实体中找不到密钥路径错误。非常感谢您提供任何建议。

What would be the best strategy for summing the difference of two date properties in a Core Data entity? I have a "numHours" calculated property on the "appt" class but not in the xcdatamodel. The code below fails with a "keypath not found in entity" error. Many thanks for any advice.

- (float)numHours {
    float hours = ([self.endTime timeIntervalSinceDate:self.startTime] - [self.durationOfBreak intValue]) / 3600.00;
    return hours;
}



尝试获取 numHours属性的总和



attempt at fetching sum of "numHours" property

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"appt" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate *datePredicate = [NSPredicate predicateWithFormat:@"date >= %@ && date < %@", self.startDate, self.endDate];
[request setPredicate:datePredicate];
[request setResultType:NSDictionaryResultType];

NSExpression *numHoursPath = [NSExpression expressionForKeyPath:@"numHours"];
NSExpression *hoursSum = [NSExpression expressionForFunction:@"sum:"
                                                   arguments:[NSArray arrayWithObject:numHoursPath]];

NSExpressionDescription *debitExpressionDescription = [[NSExpressionDescription alloc] init];
[debitExpressionDescription setName:@"totalhours"];
[debitExpressionDescription setExpression:hoursSum];
[debitExpressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:debitExpressionDescription]];
[debitExpressionDescription release];

NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error]; 


推荐答案

Jeffery,

您不能基于模型中实际上没有的属性进行提取。错误消息在实体中找不到密钥路径明确地说。您可以通过浏览SQLite数据库来自己确认这一点,并且会看到没有要查询的SQL属性。因此,您的提取请求必须失败。 NSExpression * numHoursPath 是有效的表达式。获取收藏集后,即可将其应用于收藏集。您只是不能在获取请求中使用它们。

You cannot fetch based upon an attribute that isn't actually in the model. The error message, "keypath not found in entity," plainly says this. You can confirm this for yourself by browsing the SQLite DB and you'll see there is no attribute for the SQL to query. Hence, your fetch request must fail. NSExpression *numHoursPath is a valid expression. It can be applied to collections after you've fetched them. You just cannot use them in a fetch request.

Andrew

这篇关于如何对计算所得的属性求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆