如何使用@sum与CoreData [英] How to use @sum with CoreData

查看:94
本文介绍了如何使用@sum与CoreData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Week模型,将Day作为子对象。在周模型中有天关系属性来访问所有相关的Day对象。日模型具有duration属性。

I have Week model that has Day as child objects. There is "days" relation property in Week model to access all associated Day objects. Day model has duration property.

如何计算指定Week对象的一天的持续时间总和?这将是非常好的代码示例如何创建一个谓词对象与@sum函数。

How can I figure out sum of day's durations for specified Week object? It would be great to have code example how to create a predicate object with @sum function.

也可能有计算weekDuration属性在Week类给定价值
的相关日期在获取期间的总和?

Also is it possible to have "calculated" weekDuration property on Week class that given value of sum of related day's durations during fetch? It would be most elegant solution for that problems, but I don't believe that is possible with CoreData.

推荐答案

这里是一个很好的解决方案,

Here is an example of how you would setup your query to find only weeks where the sum of the duration of the days is greater than 100.

NSManagedObjectContext *context = ...;
NSManagedObjectModel *model = ...;
NSFetchRequest *fr = [[NSFetchRequest alloc] init];
fr.entity = [model.entitiesByName objectForKey:@"Week"];

//This predicate will be compiled into pure SQL
fr.predicate = [NSPredicate predicateWithFormat:@"days.@sum.duration > 100"];

NSError *error = nil;
NSArray *results = [context executeFetchRequest:fr error:&error];
if (error) {
  NSLog(@"ERROR: %@", error);
}
NSLog(@"Results: %@", results);

你可以用类似的方法实现计算属性,只需将它添加到NSManagedObject子类中,周实体:

You can actually implement the computed property in a similiar way, just add this to the NSManagedObject subclass backing your Week entity:

- (NSNumber *) duration {
  return [self valueForKeyPath:@"days.@sum.duration"];
}

这篇关于如何使用@sum与CoreData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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