I'm trying to dynamically change the sort order to sections SwiftUI list.
The Core Data model consists of an Item
Entity with a group
and timestamp
attribute.
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@State var counter: UInt32 = 0
@State var order: SortOrder = .reverse
@SectionedFetchRequest(
sectionIdentifier: \.group!,
sortDescriptors: [SortDescriptor(\.timestamp, order: .reverse)],
predicate: nil,
animation: .default
)
private var items: SectionedFetchResults<String, Item>
var body: some View {
NavigationView {
List {
ForEach(items) { section in
Section(header: Text("\(section.id)")) {
ForEach(section) { item in
NavigationLink {
VStack {
Text("Item at \(item.timestamp!, formatter: itemFormatter)")
Text("\(item.group!)")
}
} label: {
VStack {
Text(item.timestamp!, formatter: itemFormatter)
}
}
}
}
}
}
.navigationTitle("Sectioned List")
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
ToolbarItem(placement: .principal) {
Button(action: toggleSortOrder) {
Label("Sort Oder", systemImage: "arrow.up.arrow.down")
}
}
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
newItem.group = "Group #\(counter)"
counter = (counter + 1) % 3
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func toggleSortOrder() {
order = order == .reverse ? .forward : .reverse
items.sortDescriptors = [SortDescriptor(\.timestamp, order: order)]
}
}
As soon as I toggle the sort order, the app crashes with the following error code. The same code with a non-sectioned list works perfectly. In UIKit applications there was a possibility to set tableView.beginUpdates()
and tableView.endUpdates()
. Is there any similar functions available in SwiftUI?
2022-01-24 22:09:17.323096+0100 SectionedListSortOrder[69887:2007668] *** Assertion failure in -[_UITableViewUpdateSupport _computeRowUpdates], UITableViewSupport.m:568
2022-01-24 22:09:17.347996+0100 SectionedListSortOrder[69887:2007668] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView internal inconsistency: encountered out of bounds global row index while preparing batch updates (oldRow=8, oldGlobalRowCount=8)'