How to sort SwiftUI Table with Data from Core Data FetchResult

I habe the following code :

    
    @Environment(\.managedObjectContext) private var context
    @FetchRequest(fetchRequest: Club.fetch(NSPredicate.all)) private var clubs: FetchedResults<Club>

    @State private var selectedClubs = Set<Club.ID>()
    @State var sortOrder: [KeyPathComparator<Club>] = [
            .init(\.city, order: SortOrder.forward)
        ]
    
var body: some View {
        VStack {
            Text("Clubs")

            Table(clubs, selection: $selectedClubs, sortOrder: $sortOrder) {
                TableColumn("Club ID", value: \.clubId)
                                TableColumn("Name", value: \.name)
                                TableColumn("Short Name", value: \.shortName)
                                TableColumn("Acronym", value: \.acronym)
                                TableColumn("City", value: \.city)
            }.onChange(of: sortOrder) { newValue in
                print(newValue)
            }

            
        }
    }
}

How can I enable column sorting? The example app from wwdc does not use Core Data.

This confused me based on the tutorial as adding the sortOrder seemed to make everything work. You need to make sure that the sort order is actually fed back into the data variable.

Under your fetch request have a data model that changes with the sort order

var tableData: [Club] {
    return clubs.sorted(using: sortOrder)
}

Then replace the table data with the above reference, like in the below.

Table(tableData, selection: $selectedClubs, sortOrder: $sortOrder)

Read the Supporting Sorting in Tables section of the documentation again. It recommends that you add an onChange modifier and perform the sorting there:

.onChange(of: sortOrder) { sortOrder in
    clubs.sort(using: sortOrder)
}

Check this: https://developer.apple.com/forums/thread/716156

I had the same problem. The solution shown worked for me. Don't love it, seems hacky, there must be a better way, BUT: it works.

There is no extra state for the sort required, you can bind directly to the fetch's sort descriptors, e.g.

Table(clubs, selection: $selectedClubs, sortOrder: $clubs.sortDescriptors) {

The results and the table will update automatically.

Unfortunately there is an issue where if the View containing the FetchRequest is re-init then the sortDescriptors get reset to their default. I'm not sure if that is a design flaw in FetchRequest or we are supposed to make our own @State for the sort in the view above and pass it in as a binding and use the value in the FetchRequest and using the binding to the binding in the Table, e.g.

@Binding var sortDescriptors: [SortDescriptor<Item>]

init(sd: Binding<[SortDescriptor<Item>]>) {
    _items = FetchRequest(sortDescriptors: sd.wrappedValue)
    _sortDescriptors = sd
}
How to sort SwiftUI Table with Data from Core Data FetchResult
 
 
Q