问题: 当我将所选对象的引用添加到子项后保存 viewContext 时,避免 SwiftUI 列表返回到开头的最佳方法是什么?
它应该如何工作: 想法是,用户从 SwiftUI 列表中选择 Item_general 或在工作表上创建自己的 Item_general,然后选择 Item_ocurrence 或创建 Item_size,并在下一步中创建 Item_ocurrence 的剩余属性。
Item_general 是一对多:Item_ocurrence
Item_ocurrence 是多对一:Item_size
我的 Item_general 列表定义如下:
private var items_request: FetchRequest<Item_general>
private var items: FetchedResults<Item_general>{items_request.wrappedValue}//FetchedResults<Item_general>
....
init(categoryGUID: UUID) {
self.categoryFilterString = categoryGUID.uuidString
self.items_request = FetchRequest(entity: Item_general.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Item_general.name, ascending: true)], predicate: NSPredicate(format: "category.guid = %@", self.categoryFilterString))
}
....
var body: some View {
NavigationView {
VStack {
List {
ForEach(items) { item in
NavigationLink {
// It may be null right after deleting object
ItemOccurrenceSearchView(item: item, item_guid: item.guid!, shouldSynchronizeGlobally: true)
} label: {
HStack {
Text(item.icon ?? "")
Text(item.name ?? "")
}
}
发现问题: 当我只有单边关系时,从 Item_occurrence 到 Item_general,一切都运行良好。但我开始创建 CoreData 对象的反转。当在 Item_general 上创建反转以链接到许多 Item_ocurrence 时,然后通过
添加关系
item.addToItem_ocurrence(newOccurrence)
保存 Item_ocurrence 后,列表返回到开头。为什么?我没有修改 Item_general,只是修改其尚未选择的子关系。
let newSize = Item_size(context: viewContext)
newSize.guid = UUID()
newSize.weight_gram = Int32(weight_gram)
newSize.capacity_milliliter = Int32(capacity_volume)
newSize.amount = Int32(amount)
let newOccurrence = Item_occurrence(context: viewContext)
newOccurrence.guid = UUID()
newOccurrence.kcal = 0
newSize.addToItem_ocurrence(newOccurrence)
// this line makes my list going back to select of Item_general
item.addToItem_ocurrence(newOccurrence)
do {
try viewContext.save()
} catch {
}
我检查了用户选择的项目的内存地址,保存数据库上下文后它们没有改变。视图 ID 也没有改变。无论我是否添加 Item_general.guid 作为视图 Id,或者将其保留为未分配,只有当 Item_general 上存在反转并且我使用
item.addToItem_ocurrence(newOccurrence)
添加关系时才会出现问题。
我暂时删除了 Item_general 到 Item_ocurrence 的反转并删除了
item.addToItem_ocurrence(newOccurrence)
并以这种方式简单地关联对象:newOccurrence.item = item
无论如何,我觉得我应该创建这个反转并找到一种方法来不使父项列表无效。欢迎任何帮助。感谢您花时间阅读这篇文章。
我没有找到我想要的东西,但必须改变我的方法中的一些事情: