How to create an extension to deal with multiple core data entities
I have two core data entities named Car
and Owner
, both, obviously NSManagedObject
and as all core data entities, all are @Observable
by default.
I have created a class where I was observing one of these entities, something like:
class RadioControlModel {
@ObservedObject var carEntity:Car
// ... bla bla
init(_ carEntity:Car, _ name:String) {
self.carEntity = readCarEntityWith(name)
}
}
this class is the model of a radio control that allows the user to switch the state of a boolean value of the Car
entity.
Now I need to do the same to the Owner
entity, that is, to use this class to change a boolean value of this class but the init
is tied to Car
. How do I declare this as generic so RadioControlModel
can accept any core data entity, not just of type Car
.
My problem here is to do so and continue to have the variable @Observable
, that is, responding to changes.
Solution 1:
Try this:
class RadioControlModel<T: NSManagedObject> {
@ObservedObject var carEntity:T
// ... bla bla
init(_ carEntity:T, _ name:String) {
self.carEntity = readCarEntityWith(name)
}
}