核心数据关系 [英] Core Data sum in relationship

查看:140
本文介绍了核心数据关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类别实体有很多费用。我想得到某一个月中某个类别的所有费用的总和:

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
{
...

- (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"];

}

此代码的问题是它抛出异常,因为显然不是在关系上使用@sum的方式。

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。很可能,你刚刚有另一部分的关键错误,例如。 费用而不是费用。或者,您可能正在提取错误的实体。

Your using the @sum with the correct syntax. Most likely, you have just got another part of the keypath wrong e.g. "expenses" instead of "expense". Alternatively, you may be fetching the wrong entity.

如果你想做的是获取这个总和,做一个属性获取并设置你的返回类型为字典。 (请参阅NSFetchRequest和Core Data Programming Guide)文档。它返回一个字典数组,其唯一的关键是属性名称,其唯一的值是一个被管理对象的被选属性的值。它比抓取完整对象更快,使用更少的资源。

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. 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. It's faster and uses fewer resources than fetching full objects.

这篇关于核心数据关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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