【问题标题】:SwiftUI Core Data does not refresh "one to many" relations properly and lists are not refreshedSwiftUI Core Data 没有正确刷新“一对多”关系并且列表没有刷新
【发布时间】:2020-10-04 01:16:55
【问题描述】:

我试图找出我可能做错了什么(或者,当然,误解了关系、获取和所有内容)。

在第一次搜索时,当我阅读问题的标题时,我希望这个问题可以帮助我,但我错了:

SwiftUI TabView with List not refreshing after objected deleted from / added to Core Data

无论如何...

在我的应用程序中,当我触摸客户项目时,详细视图会正确显示其数据。如果我更改任何属性并返回第一个视图,它会正确更新。

当我添加新位置或删除现有位置之一时,我的问题就开始了。当我回到第一个视图时,消费者现有位置的数量没有更新。当我关闭并重新打开应用程序时,所有数据都正确显示。

正如我所说,我的 Core Data 模型有 2 个实体,如下所示:

实体:客户 id:字符串 名称:字符串 locationList: [Location](对多(Location),级联)

实体:位置 id:字符串 地址:字符串 fromCustomer:客户(to-One(客户),无效)

这是显示客户列表的视图:


struct CustomerList: View {

    @Environment(\.managedObjectContext) var moc

    @FetchRequest(
        entity: Customer.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Customer.name, ascending: true),
        ]
    ) var customerList: FetchedResults<Customer>

    var body: some View {

        VStack{
            CustomerArea
        }
        .navigationBarTitle(Text("Customers"), displayMode: .inline)
        .navigationBarItems(leading: btnCreate, trailing: btnNew)

    }

    var CustomerArea: some View {

        List{

            ForEach(customerList, id: \.id) { customer in

                NavigationLink(
                    destination: LocationList(selectedCustomer: customer)
                ) {
                    VStack(alignment: .leading){

                        Text("\(customer.name ?? "?")").font(.headline)

                        HStack{

                                    Spacer()
                                    Text("Locations: \(customer.locationList?.count ?? 0)")
                                        .font(.footnote)

                                }

                    }.padding()
                }

            }.onDelete(perform: self.removeCustomer)

        }

    }

    private func removeCustomer(at offsets: IndexSet) {

        for index in offsets {
            let obj = customerList[index]
            self.moc.delete(obj)
        }

        try? self.moc.save()

    }

}


最后,这是我的 LocationList 视图:


struct LocationList: View {

    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    @Environment(\.managedObjectContext) var moc

    var requestLocations : FetchRequest<Location>
    var locationList : FetchedResults<Location>{requestLocations.wrappedValue}

    var selectedCustomer: Customer

    init(selectedCustomer: Customer){

        self.selectedCustomer = selectedCustomer

        self.requestLocations = FetchRequest(
            entity: Location.entity(),
            sortDescriptors: [],
            predicate: NSPredicate(format: "fromCustomer.id == %@", selectedCustomer.id!)
        )

    }

    var btnNewLocation : some View { Button(action: {

        let object = Location(context: self.moc)
        object.id = UUID().uuidString
        object.address = UUID().uuidString
        object.fromCustomer = self.selectedCustomer

        try? self.moc.save()

    })  {
        Image(systemName: "plus.circle.fill")
        }
    }

    var body: some View {

        VStack{

            List{

                ForEach(locationList, id: \.id) { location in

                    VStack(alignment: .leading){
                        Text("\(location.address ?? "?")").font(.headline)
                        .onTapGesture {

                            print("Tapped and changed selected parent object")

                            self.selectedCustomer.name = "Changed"

                            try? self.moc.save()

                            self.presentationMode.wrappedValue.dismiss()

                        }

                    }.padding()

                }
                .onDelete(perform: removeLocation)

            }


        }
        .navigationBarTitle(Text("\(selectedCustomer.name ?? "?")"), displayMode: .inline)
        .navigationBarItems(trailing: btnNewLocation)
    }

    private func removeLocation(at offsets: IndexSet) {

        for index in offsets {

            let obj = locationList[index]

            self.moc.delete(obj)

        }

        try? self.moc.save()

    }

}


这是第一个视图。想象一下我触摸了最后一项:

没有与所选客户关联的位置:

所以,我添加了新项目:

位置的数量仍然为零,但应该是1:

【问题讨论】:

  • ciao,你知道,核心数据的一个巨大缺点是关系不,重复不,触发控制器。只有“立即”字段触发。我不完全遵循你的阐述,但也许它是相关的? (关于这部剧有很多问题,例如stackoverflow.com/questions/60277521)
  • @Fattie,我的英语没有我希望的那么好,所以请提前道歉,因为我没有正确理解“即时字段”的含义。您的意思是这是预期的行为,核心数据关系仅在我更改子项时受到影响?
  • ciao Boni,你的英语比美国的每个人都好 :) 在这里阅读:stackoverflow.com/questions/60277521 core data 只有在你改变字符串、int 等字段时才会触发控制器,如果你改变了一个 关系 它不会触发控制器。这是所有 iOS 中最奇怪的事情之一。让我重复一遍:我不是 100% 理解你的问题,但是,这可能是问题!!!
  • Boni,请注意这个 QA:stackoverflow.com/questions/7533849 在 cmets 你可以看到我说“这一定是个笑话?!” :) 买真货真奇怪
  • 我有一个简单的解决方案(字面意思是几行代码),我在这里详细给出了这个问题:stackoverflow.com/a/65309334/7965564。您可以修改我的解决方案以适用于您的情况。我正在使用专用的模型控制器类并在后台上下文中进行工作,但很容易根据您的情况进行修改。

标签: swift core-data swiftui relationship one-to-many


【解决方案1】:

iOS 中的一个巨大惊喜:核心数据控制器仅适用于基本字段。奇怪但真实。

令人难以置信的是,CoreData 不会根据关系进行更新。

只有基本字段(int、string 等)。

你可以看到很多关于这个奇怪问题的 QA 和文章,例如:

NSFetchedResultsController with relationship not updating

“就是这样”。

已经有很多尝试解决这种奇怪的情况。没有真正的解决方案。 NSFetchedResultsController“就是这样”——它只适用于基本字段(字符串、整数等)。

不幸的是,情况就是这样。

注意:如果我误解了这里的问题,对不起。但我相信这就是问题所在。

【讨论】:

  • 太棒了,小胖子!虽然没有解决我的问题的“好方法”(我的意思是,任何解决它的方法都会看起来很老套),但我会将这个问题标记为“已回答”,因为您带我到了正确的地方。 10 倍很多!
  • Ciao Boni,核心数据是个大问题!!
  • 希望下一次 WWDC 能为我们带来大量的 CD 改进。
【解决方案2】:

创建一个新结构XXXView,将关系对象设置为属性。然后它会刷新。

【讨论】:

  • 您可以在您的答案中添加一些进一步的解释/说明以使其有价值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
相关资源
最近更新 更多