Instead of using UserDefaults to save the PersistentIdentifier, you might want to use AppStorage.
https://developer.apple.com/documentation/swiftui/appstorage/init(_:store:)-9lku2
@Model class Recipe { ... }
struct RecipeList: View {
@Query var recipes: [Recipe]
@AppStorage("selectedID") var selectedRecipeID: Recipe.ID?
var body: some View {
List(recipes, selection: $selectedRecipeID) { recipe in
RecipeDetail(recipe)
}
}
}
or
let selectedRecipeID = AppStorage<PersistentIdentifier?>("selectedID").wrappedValue
Post
Replies
Boosts
Views
Activity
I also faced the same problem with this code.
struct ContentView: View {
@SectionedFetchRequest(
sectionIdentifier: \Item.category!,
sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: true)],
animation: .default)
private var sections: SectionedFetchResults<String, Item>
var body: some View {
List {
ForEach(sections) { section in
Section(content: {
ForEach(section) { item in
Text(item.name!)
}
}, header: {
Text(section.id)
})
}
}
}
}
↓ SOLUTION: add SortDescriptor
sortDescriptors: [NSSortDescriptor(keyPath: \Item.category, ascending: true),
NSSortDescriptor(keyPath: \Item.name, ascending: true)],
I don't know why, but adding a SortDescriptor for the category to the beginning of the array worked fine.
I hope it helps.
ADD:
It is written in the document.
Be sure that you choose sorting and sectioning that work together to avoid discontiguous sections.
https://developer.apple.com/documentation/swiftui/sectionedfetchrequest