Search code examples
swiftcore-dataswiftuiswiftui-list

Core Data, @Environment(\.managedObjectContext), onMove


I using "Core Data" to save the app data and present it in a list using "ForEach", I give the "Entity" "index" attribute so I can sort the data with order, I can delete the data using ".onDelete(perform: deleteList)" as shown in the code bellow, but I have no idea how to implement ".onMove", any one can help or give me an example code or anything.

struct ListsView: View {

    @FetchRequest(entity: ListOfTasks.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ListOfTasks.index, ascending: true)]) private var lists: FetchedResults<ListOfTasks>
    
    @Environment(\.managedObjectContext) private var viewContext

var body: some View {
                    Section {
                        ForEach(self.lists, id: \.self) { list in
                            Text("\(list.wrappedTitle)")
                        }
                        .onDelete(perform: deleteList)
                    }
}

    func deleteList(at offsets: IndexSet) {
        for offset in offsets {
            let list = lists[offset]
            self.viewContext.delete(list)
        }
        try? viewContext.save()
    }
}

Solution

  • Here's what worked for me, trying to use your names is is something like this:

    .onMove { 
        // make an array from the core data entity, clever part
        var revisedItems: [ ListOfTasks ] = lists.map {$0} 
        // Do normal move action on array
        revisedItems.move(fromOffsets: $0, toOffset: $1)
        // Update index elements to correct order
        for i in 0..<revisedItems.count { revisedItems[i].index = i }
        try? viewContext.save()
    }