Post not yet marked as solved
Post marked as unsolved with 1 replies, 332 views
After adding an element to an array, the List displaying its data is refreshed, the last element is always selected (according to the sort order) and not the last inserted element, even if I update the selection variable programmatically in the addItem method. To better track the issue, I added an .onChange event handler in which it is possible to observe that after the insertion of a new element, the selection variable changes twice. I prepared a sample project as a variant of the template provided by Xcode for MacOS App with CoreData. You can replace the ContentView of the template with the one below. Thank you.
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: false)],
animation: .default)
private var items: FetchedResults<Item>
@State var counterSel:Int = 0
@State var selection:Item?
var body: some View {
NavigationSplitView {
List(Array(items), id:\.id, selection: $selection) { item in
NavigationLink(value: item) {
Text(item.timestamp!, formatter: itemFormatter)
}
}
} detail: {
if let _ = selection {
Text("Item at \(selection!.timestamp!, formatter: itemFormatter)").id(selection)
}
}
.toolbar {
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
.onChange(of: selection) { oldValue, newValue in
counterSel += 1
print("Counter: \(counterSel)")
if let _ = newValue {
print("Id: \(newValue!.objectID)")
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
selection = newItem
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()