在SwiftUI中,View
我有一个List
基于@FetchRequest
显示Primary
实体数据和关联Secondary
实体的Via 关系的数据。在View
其List
被正确地更新,当我添加一个新的Primary
实体,新的相关辅助实体。
问题是,当我Secondary
在详细视图中更新连接的项目时,数据库得到更新,但是更改未反映在Primary
列表中。显然,@FetchRequest
不会被另一个视图中的更改触发。
此后,当我在主视图中添加新项目时,以前更改的项目最终得到更新。
解决方法是,我另外Primary
在详细视图中更新实体的属性,并且更改正确传播到Primary
视图。
我的问题是:如何@FetchRequests
在SwiftUI核心数据中强制所有相关的更新?特别是当我无权直接访问相关实体时@Fetchrequests
?
import SwiftUI
extension Primary: Identifiable {}
// Primary View
struct PrimaryListView: View {
@Environment(\.managedObjectContext) var context
@FetchRequest(
entity: Primary.entity(),
sortDescriptors: [NSSortDescriptor(key: "primaryName", ascending: true)]
)
var fetchedResults: FetchedResults<Primary>
var body: some View {
List {
ForEach(fetchedResults) { primary in
NavigationLink(destination: SecondaryView(primary: primary)) {
VStack(alignment: .leading) {
Text("\(primary.primaryName ?? "nil")")
Text("\(primary.secondary?.secondaryName ?? "nil")").font(.footnote).foregroundColor(.secondary)
}
}
}
}
.navigationBarTitle("Primary List")
.navigationBarItems(trailing:
Button(action: {self.addNewPrimary()} ) {
Image(systemName: "plus")
}
)
}
private func addNewPrimary() {
let newPrimary = Primary(context: context)
newPrimary.primaryName = "Primary created at \(Date())"
let newSecondary = Secondary(context: context)
newSecondary.secondaryName = "Secondary built at \(Date())"
newPrimary.secondary = newSecondary
try? context.save()
}
}
struct PrimaryListView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
return NavigationView {
PrimaryListView().environment(\.managedObjectContext, context)
}
}
}
// Detail View
struct SecondaryView: View {
@Environment(\.presentationMode) var presentationMode
var primary: Primary
@State private var newSecondaryName = ""
var body: some View {
VStack {
TextField("Secondary name:", text: $newSecondaryName)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.onAppear {self.newSecondaryName = self.primary.secondary?.secondaryName ?? "no name"}
Button(action: {self.saveChanges()}) {
Text("Save")
}
.padding()
}
}
private func saveChanges() {
primary.secondary?.secondaryName = newSecondaryName
// TODO: ❌ workaround to trigger update on primary @FetchRequest
primary.managedObjectContext.refresh(primary, mergeChanges: true)
// primary.primaryName = primary.primaryName
try? primary.managedObjectContext?.save()
presentationMode.wrappedValue.dismiss()
}
}
没有帮助,抱歉。但是我遇到了同样的问题。我的详细信息视图具有对所选主要对象的引用。它显示了辅助对象的列表。所有CRUD功能在Core Data中均可正常运行,但不会反映在UI中。希望获得更多有关此的信息。
—
PJayRushton
您是否尝试过使用
—
kdion4891
ObservableObject
?
我尝试在详细视图中使用@ObservedObject var primary:Primary。但是更改不会传播回主视图。
—
比约恩B.