Question

I need to sort my objects into sections using

[[NSFetchedResultsController alloc] initWithFetchRequest:request 
                                    managedObjectContext:context 
                                      sectionNameKeyPath:sectionName 
                                               cacheName:nil];

I would like to sort them by their class. For example, objects of type MyObjectType go into one section and objects of type OtherObjectType go into a second section, where both object types will appear in the results because OtherObjectType inherits from MyObjectType. Passing @"class" as the sectionNameKeyPath parameter in the above method appears to work. However, to get the proper sorting I also need the NSFetchRequest's sort descriptor to sort based on class:

NSSortDescriptor *sectionDescriptor = [NSSortDescriptor
                                       sortDescriptorWithKey:@"class"
                                       ascending:YES];

Using this sort descriptor gives me the error Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath class not found in entity.

For clarity, here is the full chunk of code that I would like to work:

  NSFetchRequest* myRequest = [[NSFetchRequest alloc] 
                                 initWithEntityName:@"myEntityName"];

  NSSortDescriptor *nameDescriptor = [NSSortDescriptor 
                                      sortDescriptorWithKey:@"myName"
                                      ascending:YES];

  NSSortDescriptor *sectionDescriptor = [NSSortDescriptor
                                           sortDescriptorWithKey:@"class"
                                           ascending:YES];
  request.sortDescriptors = @[sectionDescriptor, nameDescriptor];

  [[NSFetchedResultsController alloc]
     initWithFetchRequest:myRequest
     managedObjectContext:myContext
     sectionNameKeyPath:@"class"
     cacheName:nil];
Was it helpful?

Solution

Keep in mind that you can only do this if you are using one entity and its sub entities, because NSFetchRequest needs an entity to search for (you can specify to also search for subentities).

You need to declare a property that identifies the proper type of record you wish to retrieve and regroup. Because class is a runtime value, you need to be able to use an identifier to be used in the underlying store. So, in your particular case, I would use a constant (string or number)property on the parent entity of all the sub entities to identify which subgroup this record belongs to.

OTHER TIPS

You can't do this with a single FRC as NSFetchRequest can only be tied to a single NSManagedObject subclass. Instead you can use multiple fetched results controllers and manually set the section indexes when looking up an object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top