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 initinitializer 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
wrotecopy-pasted a sample project that hides the context from model custom classes: branch 10583736.(it’s not final production code, just a quick example, don’t expect it to deal with multithreading or weird errors)
Hiding the context to custom classes is just a matter of defining custom methods to deal with every situation where you normally will request the context and use it.
You can define a class for the store layer without exposing the context:
I suggest to use a common ancestor for all your custom model classes to save some typing. This class can be the only one that interacts with
DataStoredirectly. It doesn’t have access to the context.Finally your model custom classes defines any method you need probably taking advantage of whatever is provided by the superclass:
The master branch has a more usual approach where model classes obtain the context and work with it.