Most apps I've written that use Core Data follow the common pattern - the model classes inherit from NSManagedObject
and are created by insertion into an NSManagedObjectContext
.
Since I'm evaluating a couple of different persistence options on a new side project, I'd love to find a way to separate out the Core Data implementation from the rest of the code. For example, I might instead use the concept of a DataStore
, defined using a protocol. It requires that any implementations provide certain functionality. For example getCars
, addCar
, and deleteCar
. The app shouldn't need to know whether getCars
is fetching from Core Data, Realm, a local file, etc.
One of the immediate problems I've run into with a Core Data implementation of DataStore
is that as soon as Car
is added as an entity to the data model, I can't create a Car
object except via the designated initializer, which expects a context to insert into. This obviously won't fly, since the whole point is to separate any knowledge of the NSManagedObjectContext
etc from the various view controllers and other classes.
I was thinking about using some other name for all my the Core Data entities (e.g. CDCar
) and then adding a bunch of code for mapping to/from CDCar
and Car
. Or perhaps making a protocol for Car
for general use in the app, to which CDCar
will conform. Is there a more common approach to this?
Adding a parallel entity adds a lot of complexity, to the point where it's not clear that the decoupling would be a net benefit.
What I'd do is include factory methods on the DataStore
class to create instances on demand. Instead of non-DataStore
code creating a Car
directly, it'd call a new createCar
method on DataStore
. DataStore
does whatever it needs to do to create a valid instance and returns the result. That would probably mean you don't need addCar
since you wouldn't be creating instances outside of DataStore
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With