'Dynamic sort descriptor FetchRequest SwiftUI

I'm having trouble figuring out how to dynamically update Core Data's FetchRequest's NSSortDescriptor in SwiftUI. I'm not sure if setting it in .onAppear is the correct way which it doesn't as I'm seeing a strange rearranging of my list. I'm using an AppStorage variable to store my sorting then I set the NSSortDescriptor .onAppear, and save when state changes. Also I detect any changes in my Picker selection and apply it to my FetchRequest configuration's sort descriptor like Apple describe's here. If I remove the FetchRequest's animation I don't see the strange rearranging but I also don't get any animations which doesn't look nice. I'm really unsure how to solve this or if I'm even doing this right.

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext
    // Set default sort descriptor as empty because it's set in onAppear
    @FetchRequest(
        sortDescriptors: [],
        animation: .default) // or set to .none
    private var items: FetchedResults<Entity>
    @AppStorage("sortby") var sortby: SortBy = .title
    var body: some View {
        NavigationView {
            List {
                ForEach(items) { item in
                    Text(item.title)
                }
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    ForEach(sort.allCases) { sort in
                        Button(sort.title, action: {
                            sortby = sort
                        })
                    }
                }
            }
            // When sort changes set the new value here
            .onChange(of: sortby, perform: { value in
                items.nsSortDescriptors =  //NSSortDescriptor here
            })
            // Set initial sort descriptor here
            .onAppear(perform: {
                items.nsSortDescriptors =  //NSSortDescriptor here
            })
        }
    }
}

FetchRequest's animation is set to default and rearranging.

animation sorting issue

FetchRequest's animation is set to none, it works but then no animations become available when sorting.

sorting no animation



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source