-1

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. :)

Alexnnd
  • 429
  • 4
  • 13
  • https://developer.apple.com/wwdc21/10017 – lorem ipsum Sep 10 '22 at 20:34
  • Thanks @loremipsum for your comment. I can clearly see that this might be the best way to sort a FetchRequest (recommended by Apple). Unfortunately, I'm not able to convert the example to my case, this is out of my reach (development level). But thanks again for the link. :) – Alexnnd Sep 11 '22 at 12:24

1 Answers1

1

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.

malhal
  • 26,330
  • 7
  • 115
  • 133
  • Thanks @malhal for this solution. I tried it and it works like a charm! I just had to add `:of` for `.onChange(of: sortTitle)` and the model name before `.title` and `.date`. But I'm wondering something: you're trying to tell me that this solution isn't the best and can cause some problems? What problems? Thanks again! – Alexnnd Sep 11 '22 at 12:28
  • if the View containing the @FetchRequest is re-init, the change made to the sortDescriptors is lost. – malhal Sep 11 '22 at 14:00
  • What do you mean by a "re-init"? – Alexnnd Sep 11 '22 at 14:48
  • var body some View { FetchView() } – malhal Sep 11 '22 at 15:43