How To Save List Ordering in SwiftUI to CoreData

In this post, we will learn how to save the list order when customizing the list order when you drag the cells and save those changes back to CoreData.

First, we create a new Entity from CoreData. A simple Item entity with a couple of attributes

  • order (Integer 16)
  • timestamp (Date)

Next, we will create a Persistence manager struct to handle the CoreData persistence.

We will add a couple of functions to make a request with a NSSortDescriptor with the “order” attribute as the key and another function to simply save the viewContext changes.

Once that initial setup of the CoreData is done, we can create a List that iterates to all the Items. Create a new class and make it an ObservableObject. We will load the items on initilization.

Finally, we can create our view using SwiftUI.

Create the StateObject and call the ContentVM

Create a NavigationView and add List which we will add ForEach to iterate to any loaded items.

We can add .onDelete() at the end of the ForEach.

Then the .onMove() call will contain our logic for sorting.

It basically creates temporary Items from the existing Items array and reorders the index and finally saves the viewContext.

Full source code can be downloaded in github here.

Leave a Reply

Your email address will not be published. Required fields are marked *