如何正确更新详细信息视图中的 CoreData 对象? [英] How do I update a CoreData object in a detail view correctly?

查看:29
本文介绍了如何正确更新详细信息视图中的 CoreData 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个简单的应用程序,其中包含一个排序的项目列表.单击每个项目进入详细视图,单击另一个按钮更新项目的字段,该字段应重绘原始列表.

I want to have simple app that has a sorted list of items. Clicking on each item goes into a detail view, where clicking another button updates a field of an item, which should redraw the original list.

列表视图由:

import SwiftUI
import CoreData

struct ContentView: View {

    @Environment(\.managedObjectContext) var context 

    @State private var itemName: String = ""

    // get all data, sorted by date
    @FetchRequest(
        entity: Item.entity(),
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.lastEdited, ascending: true)]
    ) var allItems: FetchedResults<Item>



    var body: some View {

        NavigationView {
            List {
                ForEach (allItems) { item in
                    NavigationLink(destination: DetailView(item: item).environment(\.managedObjectContext, self.context)) {
                        Text(item.name ?? "No name given")
                    } // nav link

                }


            }
    }
}


详细视图由:


import SwiftUI
import CoreData


struct DetailView: View {


    @Environment(\.managedObjectContext) var context

    var item: FetchedResults<Item>.Element

    var body: some View {

        Button (action: {
            self.updateDate(item: self.item)

            }) {
                Text("Press me!")
            }

    } // body

    func updateDate(item: Item) {
        item.lastEdited = Date()
    } // func

} // DetailView



在详细视图上按按我"按钮会导致更新工作,列表视图也会更新,但是当我按下按钮时会发生这种情况:

Pressing the "Press Me" button on the detail view causes the update to work, and the list view to update, but this happens when I press the button:

  1. 显示带有详细信息视图的新屏幕
  2. 返回列表视图

为什么(1)会发生?我如何避免这种情况?

Why does (1) happen? How do I avoid this?

我在 xcdatamodeld 中将项目定义为实体

I have Item defined as an Entity in my xcdatamodeld

推荐答案

更改

var item: FetchedResults<Item>.Element

@ObservedObject var item: Item

这可能是因为父级正在重绘.

It likely happens because the parent is redrawing.

这篇关于如何正确更新详细信息视图中的 CoreData 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆