SwiftUI Table (macOS 12) and CoreData

Viewed 296

I have a problem with the sortOrder in Tables with FetchedResults as datasource. Currently I'm using XCode 13 beta, Deployment Target macOS 12.0. Here is my code:

struct MyTable: View {
    
    @FetchRequest(fetchRequest: Person.fetchRequest(), animation: .default) 
    var people: FetchedResults<Person>
  
    @State private var sortOrder = [KeyPathComparator(\Person.familyName)]
    @State private var selectedPersonID: Person.ID?
    
    var body: some View {
        Table(people, selection: $selectedPersonID, sortOrder: $sortOrder) {
            
            TableColumn("Nachname", value: \.familyName)
            TableColumn("Vorname", value: \.givenName)
            TableColumn("Adresse", value:\.address)
            TableColumn("Telefon 1", value:\.phone1)
            TableColumn("Telefon 2", value:\.phone2)
        }
        .onChange(of: sortOrder) {
           // --> PROBLEM: how can I implement the sortOrder with NSSortDescriptor ? <--
        }
   
    }
}

My question is: How can I implement the sort functionality in the .onChange-Method? The first attempt using people.sort(using: $0) failed. I also tried to parse the fetchedResults<Person> people into an Array:

var peopleArray: [Person] {
     Array(people)
}

But then I get an immutable value peopleArray on which I cannot sort with the .sort(using:)-Method.

Thanks for any help!

Nico

0 Answers
Related