我确信我对尝试将 SQL 逻辑应用于 Core Data 感到内疚,但即使在阅读了 Apple 文档之后我仍然不确定正确的方法。
求和 Core Data 实体中两个日期属性的差异的最佳策略是什么?我在“appt”类上有一个“numHours”计算属性,但在 xcdatamodel 中没有。下面的代码失败并出现“在实体中找不到键路径”错误。非常感谢您的任何建议。
来自appt类
- (float)numHours {
float hours = ([self.endTime timeIntervalSinceDate:self.startTime] - [self.durationOfBreak intValue]) / 3600.00;
return hours;
}
尝试获取“numHours”属性的总和
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];
最佳答案
杰弗里,
您不能根据实际不在模型中的属性进行提取。错误消息“在实体中找不到 key 路径”清楚地说明了这一点。您可以通过浏览 SQLite 数据库自行确认这一点,您会看到没有可供 SQL 查询的属性。因此,您的获取请求必须失败。 NSExpression *numHoursPath
是一个有效的表达式。它可以在你获取它们之后应用于集合。您只是不能在获取请求中使用它们。
安德鲁
关于iphone - 如何对计算出的属性求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8862341/