Steps to reproduce:
- click any item in the list to get into its detail view
- click the + button to increase the count value of the item
- go back to the item list
- [ISSUE 1] the count value of the item is not updated in the list view
- now click the item you just operated to go back its detail view
- [ISSUE 2] the item's draft value is reverted back to the origin value (Or you can say it's the value displayed in the list view)
If you remove the GeometryReader, it works normally, without that 2 issues.
The Result I want:
- The list view's count value updated after going back to the list view.
- The draft value should be the same as the item at second entry after updating count.
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
NavigationView {
List {
ForEach(items) { item in
// Not Work
GeometryReader { geo in
NavigationLink(destination: SubView(item: item)) {
HStack {
Text("\(item.timestamp!.ISO8601Format())")
Spacer(minLength: 0)
Text(String(item.count))
}
}
}
// Works
// NavigationLink(destination: SubView(item: item)) {
// HStack {
// Text("\(item.timestamp!.ISO8601Format())")
// Spacer(minLength: 0)
// Text(String(item.count))
// }
// }
}
}
}
}
}
struct SubView: View {
@ObservedObject var item: Item
@State private var draft: TmpItem
init(item: Item) {
self.item = item
self._draft = State(wrappedValue: TmpItem(count: Int(item.count)))
}
var body: some View {
VStack {
Text("\(item.timestamp!.ISO8601Format())")
Text("item: \(item.count)")
Text("draft: \(draft.count)")
Button("+") {
draft.count += 1
item.count = Int16(draft.count)
try! viewContext.save()
}
.buttonStyle(.borderedProminent)
}
}
@Environment(\.managedObjectContext) private var viewContext
}
struct TmpItem {
var count: Int
}
#Preview {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
It's base on the defualt demo code from Xcode 15.1.0 for iOS app with core data. Added a count field (Int16) to the Item object.