我遇到的问题是,当我从工作表视图更新核心数据资产对象时,更改未反映在AssetListView的UI中。 (请注意,从工作表视图插入新对象会刷新AssetListView的UI。在工作表视图中删除对象也会刷新 AssetListView的UI)唯一不起作用的操作是更新。
当核心数据对象更改时,如何更改AssetListView?
我有以下SwiftUI代码,显示了CoreData FetchRequest中的资产列表:
struct AssetListView: View {
@State private var showingSheet = false
@State private var selectedAssetId: NSManagedObjectID?
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Asset.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Asset.allocationPercentage, ascending: false)]) var assets: FetchedResults<Asset>
var body: some View {
VStack {
Form {
ForEach(assets, id: \.self) { asset in
Section {
AssetRowView(asset: asset)
.onTapGesture {
self.selectedAssetId = asset.objectID
self.showingSheet = true
}
}
}
}
}
.navigationBarTitle("Assets").sheet(isPresented: $showingSheet ) {
EditAssetView(assetId: self.selectedAssetId!)
.environment(\.managedObjectContext, self.moc)
}
}
}
}
这是一个编辑屏幕,我将其显示为SwiftUI表:
struct EditAssetView: View {
var assetId: NSManagedObjectID
@Environment(\.presentationMode) var presentationMode
@State private var name = ""
@State private var description = ""
@Environment(\.managedObjectContext) var moc
var asset: Asset {
moc.object(with: assetId) as! Asset
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Name", text: $name)
TextField("Description", text: $description)
}
}
.navigationBarTitle(Text("Edit Asset"), displayMode: .inline)
.navigationBarItems(leading: Button("Cancel") {
self.presentationMode.wrappedValue.dismiss()
}, trailing: Button("Done") {
self.presentationMode.wrappedValue.dismiss()
self.asset.name = self.name
self.asset.assetDescription = self.description
try? self.moc.save()
}
)
}
.onAppear {
self.name = self.asset.name
self.description = self.asset.assetDescription
}
}
}
这是AssetRowView的代码:
struct AssetRowView: View {
var asset: Asset?
var body: some View {
HStack {
Text(asset.name)
Text(asset.assetDescription)
}
}
}
答案 0 :(得分:4)
尝试观察Asset
(因为NSManagedObject
是-a ObservableObject
)
struct AssetRowView: View {
@ObservedObject var asset: Asset // << here !!
var body: some View {
HStack {
Text(asset.name)
Text(asset.assetDescription)
}
}
}
如果这还不够的话,可能还需要将Done
按钮的操作更新为
}, trailing: Button("Done") {
self.asset.objectWillChange.send() // << here !!
self.asset.name = self.name
self.asset.assetDescription = self.description
try? self.moc.save()
// better do this at the end of activity
self.presentationMode.wrappedValue.dismiss()
}
答案 1 :(得分:0)
我所做的是将核心数据对象传递为:
@ObservedObject var toDo: FetchedResults<ToDoModelCoreData>.Element
来自我的提取结果
@FetchRequest var todoFetchRequest: FetchedResults<ToDoModelCoreData>
这将确保 swiftUI 视图在 coredata 更新时更新