Swift:Coredata检测一段关系对象属性上的变化

发布于 2025-01-27 11:07:16 字数 945 浏览 2 评论 0原文

我有一个核心数据管理对象(租赁),它与另一个对象(lineItems)有一对一的关系。

我正在尝试检测何时添加,删除,删除或属性进行修改,以便我可以重新计入租赁中的字段。

我想从标准租赁+柯达卡拉类文件中执行此操作。

我使用KVO,NotificationCenter,Combine等看到了许多解决方案和DOCO,但是它们似乎都是从SwiftUi视图完成的,我无法理解它以在Coredataclass文件中实现。我想将此独立于视图,因为我的应用程序中有许多部分可以更改LineItem记录。

有人知道该怎么做吗?也许一些示例代码,以便我可以理解它的工作原理?

编辑:一些额外的信息:

租赁具有1个属性,一个与多个关系的关系:

  • payment -duedate(attribute)
  • lineItems(与lineItem的一到多个关系)

lineItem具有2个属性,返回租赁的逆关系:

  • date(属性)金额(属性)
  • 金额(属性)
  • 租赁(返回租赁的逆关系)

这是我生成的租赁+柯达省文件的代码:

import Foundation
import CoreData
            
@objc(Lease)
public class Lease: {
    func recalculatePaymentDueDate() {
        //some complex code to recalculate paymentDueDate field
        let result = someCalc()
        self.paymentDueDate = result
    }
}

基本上要在将LinesItem添加到或从租赁中添加到租赁或修改金额时,都希望调用RecalculatePaymentDuedate()。

I have a Core Data ManagedObject (Lease) that has a one to many relationship with another object (LineItems).

I'm trying to detect when the LineItem object changes ie is added, deleted or attributes within it modified so I can recalculate a field in Lease.

I'd like to do this from the standard Lease+CoreDataClass file.

ive seen a number of solutions and doco using KVO, NotificationCenter, Combine etc. but they all seem to be done from a swiftui view and I haven't been able to make sense of it enough to implement in my CoreDataClass file. I'd like to have this independent of the view as there are many parts of my application that could change a LineItem record.

Anyone know how to do this? maybe some example code so I can understand how it works?

Edit: some extra info:

Lease has 1 attribute and a one to many relationship:

  • paymentDueDate (attribute)
  • lineItems (one to many relationship to LineItem)

LineItem has 2 attributes and an inverse relationship back to Lease:

  • date (attribute)
  • amount (attribute)
  • lease (inverse relationship back to Lease)

This is the code for my generated Lease+CoreDataClass file:

import Foundation
import CoreData
            
@objc(Lease)
public class Lease: {
    func recalculatePaymentDueDate() {
        //some complex code to recalculate paymentDueDate field
        let result = someCalc()
        self.paymentDueDate = result
    }
}

Basically want to call recalculatePaymentDueDate() whenever a LineItem gets added to or removed from Lease or the amount modified.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文