Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order entities in Core Data data model

I am using Core Data in my application, and I have entities that need to be reordered. I have a collection view that is populated with NSManagedObjects from the data model, and this collection view can be reordered by dragging and dropping the cells. I want the order of the entities in the data model to reflect the order of the cells in the collection view. Does anyone know how I can accomplish this? I am new to Core Data, so I am still getting used to it.

like image 301
Chandler De Angelis Avatar asked Jul 19 '26 22:07

Chandler De Angelis


1 Answers

If I understand your question correctly, you may do it simply as follows:

  • add an attribute viewOrder to your entity, probably an integer type
  • update it any time the user drags and drops a cell, i.e. re-orders the collection view (& make sure to save: the NSManagedObjectContext whenever you make any changes)
  • when populating the collection view, set the NSFetchRequest property sortDescriptors to sort the results by viewOrder
  • note that if you add new managed objects, you'll have to run a fetch to count the current number in core date or to find the max viewOrder
like image 167
salo.dm Avatar answered Jul 22 '26 11:07

salo.dm



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!