简体   繁体   English

核心数据总和关系

[英]Core Data sum in relationship

I have a Category entity which has many expenses. 我有一个类别实体,有很多费用。 I want to get the sum of all expenses for a category in a given month: 我想获得给定月份中某类别的所有费用总和:

- (NSNumber *)totalForMonth:(NSDate *)date { ...

 NSPredicate *sumPredicate = [NSPredicate predicateWithFormat:@"(ANY %@ <= expenses.created_at) AND (ANY expenses.created_at <= %@)", [date beginningOfMonth], [date endOfMonth]]; NSFetchRequest *req = [[[NSFetchRequest alloc] init] autorelease]; [req setPredicate:sumPredicate]; [req setEntity:entity]; NSError *error; NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:req error:&error]; return [fetchedObjects valueForKeyPath:@"expenses.@sum.amount"]; } 

NSPredicate *sumPredicate = [NSPredicate predicateWithFormat:@"(ANY %@ <= expenses.created_at) AND (ANY expenses.created_at <= %@)", [date beginningOfMonth], [date endOfMonth]]; NSFetchRequest *req = [[[NSFetchRequest alloc] init] autorelease]; [req setPredicate:sumPredicate]; [req setEntity:entity]; NSError *error; NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:req error:&error]; return [fetchedObjects valueForKeyPath:@"expenses.@sum.amount"]; }

The problem with this code is that it throws an exception because apparently that's not the way to use @sum on a relationship. 这段代码的问题在于它抛出异常,因为显然这不是在关系上使用@sum的方法。

You might need to create a custom getter for it, and access it from there. 您可能需要为其创建自定义getter,并从那里访问它。

ie

Category.h Category.h

@property (nonatomic, readonly) NSNumber* expensesSum;    

Category.m Category.m

-(NSNumber*) expensesSum
{
    return [self valueForKeyPath:@"expenses.@sum.amount"];
}

Also, you're currently returning NSNumber * when the request returns an array of children objects I believe. 此外,当请求返回我认为的子对象数组时,您当前正在返回NSNumber *

Your using the @sum with the correct syntax. 您使用正确语法的@sum。 Most likely, you have just got another part of the keypath wrong eg "expenses" instead of "expense". 最有可能的是,你刚刚得到了密钥路径的另一部分错误,例如“费用”而不是“费用”。 Alternatively, you may be fetching the wrong entity. 或者,您可能正在获取错误的实体。

If all you want to do is fetch this sum, do an attribute fetch and set your return type to dictionary. 如果您只想获取此总和,请执行属性提取并将返回类型设置为字典。 (See NSFetchRequest and Core Data Programming Guide) docs for details. (有关详细信息,请参阅NSFetchRequest和核心数据编程指南)文档。 That returns an array of dictionaries whose sole key is the attribute name and whose sole value is the value of selected attribute of one managed object. 返回一个字典数组,其唯一键是属性名称,其唯一值是一个托管对象的selected属性值。 It's faster and uses fewer resources than fetching full objects. 它比获取完整对象更快,使用的资源更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM