Fetched results controller sectionIndexTitle based on transient attributes

I have a core data entity 'Person'. I need to customise the section index title and so I thought of creating transient attribute the separate the data into some specific section based on my own logic. But, while I create the fetch request with fetchedResultsController, and keep this transient attribute 'sectionNameKeyPath' to initialize the fetchedResultsController sectionNameKeyPath. And so, I had to make this as a key to first sort descriptor. But, this crashes the applications. Isn't it possible to use transient attributes as sectionNameKeyPath in fetchedResultsController

My crash log is.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath sectionNameKeyPath not found in entity <NSSQLEntity Person id=1>' 

You can use a transient attribute as sectionNameKeyPath for a fetched results controller. But you cannot use a transient attribute in the sort descriptor. For a SQLite based Core Data store, only non-transient attributes can be used in sort descriptors.

This is documented in Fetch Predicates and Sort Descriptors in the "Core Data Programming Guide":

The SQL store, on the other hand, compiles the predicate and sort descriptors to SQL and evaluates the result in the database itself. This is done primarily for performance, but it means that evaluation happens in a non-Cocoa environment, and so sort descriptors (or predicates) that rely on Cocoa cannot work. The supported sort selectors are ...
In addition you cannot sort on transient properties using the SQLite store.

But the first sort descriptor need not be the same as the sectionNameKeyPath, see the documentation of initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:

sectionNameKeyPath
...
If this key path is not the same as that specified by the first sort descriptor in fetchRequest, they must generate the same relative orderings. For example, the first sort descriptor in fetchRequest might specify the key for a persistent property; sectionNameKeyPath might specify a key for a transient property derived from the persistent property.

The DateSectionTitles sample code from the iOS Developer Library demonstrates how this works.

链接地址: http://www.djcxy.com/p/36122.html

上一篇: 在NSFetchedResultsController中使用基于时间的瞬态属性

下一篇: 基于瞬态属性提取结果控制器sectionIndexTitle