swiftxcodecore-dataswiftuifetchrequest

Sorting @FetchRequest (not dynamically) with SwiftUI


I tried the entire day to find the simplest solution to sort a @FetchRequest without any success!

I have tried this little modification:

@AppStorage("sortTitle") private var sortTitle = true

@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [ sortTitle ? SortDescriptor(\.title) : SortDescriptor(\.date) ]) private var items: FetchedResults<Item>

And of course it doesn't work. Actually, I'm looking for something very simple because this isn't a dynamic sorting ; it's more like a one-time sorting that can be done by toggling sortTitle from the Settings screen.

There's of course one online solution (on the link below) but I'm not good enough to understand it correctly at the moment! https://www.youtube.com/watch?v=O4043RVjCGU

Thanks, in advance, for your feedback. :)


Solution

  • This is worth a shot but to be honest @FetchRequest seems to be designed for a a ContentView that is only init once which is not the way SwiftUI is supposed to work.

    .onAppear {
        items.sortDescriptors = sortTitle ? [SortDescriptor(\.title)] : [SortDescriptor(\.date)]
    }
    .onChange(of: sortTitle) { newSortTitle in
        items.sortDescriptors = sortTitle ?  [SortDescriptor(\.title)] : [SortDescriptor(\.date)]
    }
    

    The flaw is that if the View containing this code is re-init, the change made to the sortDescriptors is lost.