I am using CoreData and have two sub-entities with a common abstract super-entity, let's call them
SuperEntity,
FirstSubEntity and
SecondSubEntity
All three entities have their own subclass of NSManagedObject
or SuperEntity
.
I'm using a NSFetchRequest
to fetch all objects of type SuperEntity
, meaning I will get a set of all FirstSubEntities
and SecondSubEntities
all jumbled together. I want to sort this set based on the entity class, like this.
<FirstSubEntity id=X>
<FirstSubEntity id=X>
<FirstSubEntity id=X>
<SecondSubEntity id=X>
<SecondSubEntity id=X>
I'm trying to set an NSSortDescriptor
with key class
:
[NSSortDescriptor sortDescriptorWithKey:@"class" ascending:YES]
Unfortunately it throws an exception
'NSInvalidArgumentException', reason: 'keypath class not found in entity <NSSQLEntity SuperEntity id=X>'
Curiously, if I instead use an NSFetchedResultsController
I'm able to set the sectionName to class
like this
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext
sectionNameKeyPath:@"class"
acheName:nil];
Which works fine. Any ideas on how to manage this with NSSortDescriptors
?
That works in the sectionNameKeyPath
because the sectionNameKeyPath
is resolved after the objects are loaded into memory. The NSFetchRequest
and its sort descriptors are done at the SQLite level which the key class
is meaningless.
Further, at the SQL level, your two entities are really in the same table so there is no way to differentiate and therefore sort them at that point.
Your only solution is to sort them in memory, not in the fetch directly. You can use a NSSortDescriptor
against the returned array from a normal fetch request and in that case I would use entity.name
instead of class
.