0
votes

I have Event model with startDate and endDate. I want to sort this event to 3 categories.

  • Current: startDate < today < endDate
  • Upcoming: today < startDate
  • Past: endDate < today

I made a transient property called status contain above logic and use this as parameter in NSFetchedResultsController

NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "status", cacheName: nil)

When I run I got this error telling me to use section as sort descriptor.

CoreData: error: (NSFetchedResultsController) The fetched object at index 2 has an out of order section name '1. Objects must be sorted by section name'

I then set this in sort descriptor and got this error, since transient can't be used as sort descriptor.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath status not found in entity '

The problem is this section are determine from 2 properties, so it can't be sort by just startDate or endDate, but both.

What is the best way to solve this problem? I have consider making this status non-transient, but this value is updated daily, I think it kind of weird to make it non-transient.

1

1 Answers

0
votes

NSFetchedResultsController cannot sort on a transient property if it is backed by SQLite (which is the usual case). The backend has to turn your sort request into a SQL query, and the query won't have access to transient properties. You either have to make status non-transient or you can't use NSFetchedResultsController for this.

See the Core Data Programming Guide: Advanced Topics: Fetch Predicates and Sort Descriptors for more.

In addition you cannot sort on transient properties using the SQLite store.