'Swift: CoreData detecting change on one-many relationship object attribute
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
