0

I have an array of object IDs and the array has the correct order.

let objectsIDs = [504, 316, 195, ...]

And I am using NSFetchedResultsController with this NSPredicate:

NSPredicate(format: "%K IN %@", #keyPath(object.id), objectsIDs)

NSFetchedResultsController requires NSSortDescriptor and I cannot use createdAt or id property to sort the objects.

How can I get NSSortDescriptor to sort the objects based on the objectsIDs array order? The objectsIDs array always have the correct order and NSSortDescriptor must depend on its order.

user10711707
  • 135
  • 1
  • 7

1 Answers1

0

How can I get NSSortDescriptor to sort the objects based on the objectsIDs array order?

You can't. What you're trying to do is cosort the array, ie sort it according to the order of another array. NSSortDescriptor doesn't do that. You have to do it. Cosorting is a well discussed problem.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Do you have suggestions on how I can do this? Adding a dedicated property to the `NSManagedObject` subclass is not practical for me as I have various scenarios where the order is different. – user10711707 Jun 04 '22 at 13:14
  • You just have to get the data in any old order and then sort. It's not going to come to you sorted from the fetch. That's my point. – matt Jun 04 '22 at 13:15
  • Examples for Swift of how to cosort: https://stackoverflow.com/questions/39273370/reorder-array-compared-to-another-array-in-swift https://stackoverflow.com/questions/43056807/sorting-a-swift-array-by-ordering-from-another-array You can readily do the same in Objective-C. – matt Jun 04 '22 at 13:16
  • Right, I see but these are regular arrays. I use `NSFetchedResultsController` and it depends on `NSSortDescriptor` to sort the objects. Is there another way to configure `NSFetchedResultsController` to sort the objects without `NSSortDescriptor`? – user10711707 Jun 04 '22 at 13:22
  • Thanks. A lot of these are written in Objective-C and I did not find anything that were relevant to me. I was thinking about what you said that I have to sort them myself as I can't get them sorted. So I could do the sorting in `controller(_:didChangeContentWith:)` as part of `NSFetchedResultsControllerDelegate` protocol. – user10711707 Jun 04 '22 at 14:20
  • Sorry, somehow I had the impression that you wanted Objective-C. – matt Jun 04 '22 at 14:55