核心数据:NSFetchRequest按对多关系计数排序 [英] Core Data: NSFetchRequest sorting by count of to-many relationship

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

问题描述

说我有一个父实体,每个实体都有许多孩子。我想让所有父母按照孩子的数量排序。类似于以下伪代码:

Say I have an parent entity, each of which have a number of children. I want to get all the parents sorted by their number of children. Something similar to the following pseudo code:

NSEntityDescription * entity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:managedObjectContext];

[[NSSortDescriptor alloc] initWithKey:@"children.count" ascending:NO];
//Execute request

有没有一种方法可以使用核心数据来构造这样的提取?如果没有办法这样做,将使用 sortedArrayUsingSelector进行排序:失去_PFBatchFaultingArray批处理大小的好处吗?

Is there a way construct a fetch like this using core data? If there is no way to do this will sorting using sortedArrayUsingSelector: loose the benefits of _PFBatchFaultingArray batch size?

谢谢,
Ben

Thanks, Ben

推荐答案

您的查询可以使用,但是(假设儿童是有缺陷的)将在 children 属性上使用键值编码方法,这将引发错误(请参阅 NSManagedObject文档,其中包含引发错误的方法列表以及对此行为的讨论),因此您需要失去批处理和故障处理的性能优势。

Your query would work, but (assuming children is faulted) would use key-value coding methods on the children property, which in turn would fire the fault (see the NSManagedObject docs for a list of methods that fire faults, and a discussion of this behavior), so you'd lose the performance benefits of batching and faulting.

您可能会考虑在父实体上维护派生属性(称为 childrenCount ),如果您的情况可行,它会反映与父母相关的孩子的数量。这不是最干净的解决方案,但是如果您将其作为NSNumber保留在父实体中,即使 children 有故障,您也可以访问它,并且可以对其进行排序直接。

You might consider maintaining a derived attribute on your parent entity (call it childrenCount) that reflects the number of children related to the parent, if this is feasible for your situation. It's not the cleanest solution, but if you keep it as an NSNumber in the parent entity you'd have access to it even if children is faulted, and you can sort on it directly.

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

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