7

I want to group the results of a NSFetchRequest by entity. The entities all share the same abstract parent. For example:

animal
|
|-cat
|
|-dog

The NSFetchRequest has includesSubentities set TRUE and entity set to animal. It is possible to set sectionNameKeyPath of NSFetchedResultsController to entity.name but it is not possible to do the same with the sortDescriptors of the NSFetchRequest due to the fact that the sortDescriptors are applied to the stored attributes (i.e. data in the database, not methods on the classes). Therefore the only way to group by entity type is to add an attribute to the superclass that subclasses can use to identify themselves.

This seems crazy as it undermines the usefulness of inheritance. I had a look in the SQLite database and the entity type is stored in the same table as the attributes so the required data is already in place.

In summary: Is it possible to sort by subclasses in an NSFetchRequest without adding additional attributes?

4

1 回答 1

2

我认为答案是否定的。

获取和排序发生在 Store 中(对于 SQLLite 存储),因此属性需要成为数据模型的一部分。来自核心数据编程指南(持久存储功能):

获取和存储类型之间存在一些交互。在 XML、二进制和内存存储中,谓词和排序描述符的评估是在 Objective-C 中执行的,可以访问 Cocoa 的所有功能,包括 NSString 上的比较方法。另一方面,SQL 存储将谓词和排序描述符编译为 SQL,并在数据库本身中评估结果。这样做主要是为了性能,但这意味着评估发生在非 Cocoa 环境中,因此依赖 Cocoa 的排序描述符(或谓词)无法工作。

此外,您不能使用 SQLite 存储对瞬态属性进行排序。

于 2011-09-19T12:01:49.073 回答