我正在處理一個具有關系的核心資料物體。問題是,然后我將一個專案附加到 UI 未更新的子陣列中。
var selectedNode : Node
var body: some View {
VStack {
ForEach(selectedNode.childrenArray) { item in
NavigationLink {
Text("Item at \(item.text!)")
} label: {
Text(item.text!)
}
}
}
.toolbar {
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
}
private func addItem() {
withAnimation {
viewContext.performAndWait {
let newItem = Node(context: viewContext)
newItem.text = "Hello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello world"
newItem.dateAdded = Date()
selectedNode.addToChildren(newItem)
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)")
}
}
}
}
正如預期的那樣,當您使用 coredata 陣列填充 View 時,它會根據 coredata 中的任何更改自動更新視圖。但是由于我們沒有直接使用 coredata 陣列來填充視圖,我應該如何更新View.
想到的一種可能的解決方案是使用謂詞來獲取屬于“子陣列”的專案,以便我們可以直接使用 coredata 陣列來填充視圖。但到目前為止我無法實作這一點。

uj5u.com熱心網友回復:
所有 CoreData 物件都是ObservableObjects,因此需要將它們包裹起來,@ObservedObject以便在View發生更改時可以重繪
@ObservedObject var selectedNode : Node
另外,請確保您正在使用@FetchRequest,NSFetchedRequestController以便可以觀察到商店的變化。NSFetchRequest不觀察商店。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354981.html
上一篇:如何在Swift中檢測Fn按鍵?
