Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSFetchedResultsController result based on array?

I would like to construct a NSPredicate or NSSortDescriptor (Core Data search) that is based on the content of an array.

The array will consists of userId:s in the right order:

[1, 2, 5, 3];

I would like to present the result for my NSFetchedResultsController in the same order.

So I will:

  1. Get the right users (I have done this)
  2. Sort the list of users based on my sorted array with userIds.

Is this possible to do, and how can I do it?

like image 614
Anders Avatar asked Aug 02 '26 05:08

Anders


1 Answers

I think that is not possible. Sorting the results of a fetch request (for a SQLite-based store) is done on the SQLite level, and can use only persistent attributes stored in the database. The sort descriptor cannot use Objective-C functions or variables.

So either

  • you add an additional attribute to your entity that describes the intended ordering (if that is possible), or
  • you sort the results according to your needs after fetching them (which means that you cannot use a fetched results controller for automatic change tracking anymore). Perhaps you can use the method described here: https://stackoverflow.com/a/15618277/1187415.
like image 174
Martin R Avatar answered Aug 03 '26 19:08

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!