How to sort the results of an NSFetchedResultsController using the order of an NSOrderedSet

1.2k Views Asked by At

NSOrderedSets save the order of the objects in the table. If you access an NSManagedObject subclass instance with a property that is an NSOrderedSet, then they will be in order.

However, there is seemingly no way to access that order using an NSSortDescriptor when creating an NSFetchRequest.

It appears from the raw SQLite DB, that order is stored in fields named Z_FOK_<relationship name>. The data is available, but it doesn't appear to be visible through the core data APIs.

Does anyone know a way to write an NSSortDescriptor that will work with a SQLite DB to return the results in the order specified by the NSOrderedSet?


Update

Related Question: NSFetchedResultsController and NSOrderedSet relationships

2

There are 2 best solutions below

4
On

I don't think that is possible. The "ordering" is associated with the to-many relationship from one entity A to another entity B, it is not a property of the target entity B. But a sort descriptor for a Core Data fetch request can only use (persistent) properties of the entity.

0
On

I've tried this in swift just now and it seemed to work for me.

var sectionsExcludingEmpty: [SurveyAnswerSection] {
    let fetchRequest: NSFetchRequest<SurveyAnswerSection> = NSFetchRequest.init(entityName: "SurveyAnswerSection")
    fetchRequest.predicate = NSPredicate.init(format: "surveyAnswer == %@ AND hidden == FALSE", self)
    fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "surveyAnswer", ascending: true) ]
    if let moc = self.managedObjectContext {
        do {
            let results = try moc.fetch(fetchRequest)
            return results
        } catch {
            fatalError("Could not get sectionsExcludingEmpty: \(error)")
        }
    } else {
        fatalError("Unable to get own managed object context")
    }
}

When I missed off the line fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "surveyAnswer", ascending: true) ] it ordered seemingly randomly, but with the line added it sorted as expected.

In my case SurveyAnswerSection has a one to ordered-many relationship with SurveyAnswer.