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

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

问题描述

我有将 Day 作为子对象的 Week 模型.Week 模型中有一个days"关系属性来访问所有关联的 Day 对象.日模型具有持续时间属性.

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.

还可以在给定值的 Week 类上计算出"weekDuration 属性获取期间相关日期的总和?对于这些问题,这将是最优雅的解决方案,但我认为 CoreData 不可能做到这一点.

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.

推荐答案

以下示例说明了如何设置查询以仅查找天数总和大于 100 的周.

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);

您实际上可以以类似的方式实现计算属性,只需将其添加到支持您的 Week 实体的 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"];
}

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

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