We have made a repository layer for interacting with Core Data that have methods such as allItems()
, addItem:(Item*)item
where item being the NSManagedObject subclass. When we need to save an item we invoke the method on the repository passing the subclass instance as an argument. However, that does not work because we can't use the init
initializer and the context is hidden inside the repository.
What is the best way to transfer objects when you have an architecture like this? Is making a ItemDTO an passing that around an option? Or are there better ways to solve this such as not using subclassed NSManagedObject at all and just use key/value that works.
I'd say the architecture you are using isn't suited to core data. To keep using it (which you should) you have to do one of two things. I am assuming your "repository layer" is implemented as a singleton, or at least that the objects creating new managed objects have access to it.
If you find yourself fighting the frameworks and coming up with excessive abstractions, you're doing it wrong.
Typically, you'd want the controllers creating the NSManagedObject
subclasses to have a pointer to the NSManagedObjectContext
. In this way, you could indeed call the initializer.
The problem with what you are trying to do is that the items cannot exist without the context. That is done purposely so that Core Data knows if you are talking about a new object or an object that is already in the persistent store.
You could use DTOs but you'd end up with a lot of duplication so it gets ugly quick. In my opinion, you should consider making your controllers aware of the Core Data context so that it can properly either retrieve or init the items (managed objects) and essentially use the NSManagedObjectContext
as your repository layer.
Remember that the NSManagedObjectContext
IS a persistence abstraction layer and you can back it up with other persistent store implementations if you want, including your own custom ones.
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