Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transport NSManagedObject subclass between classes?

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.

like image 351
LuckyLuke Avatar asked May 14 '12 12:05

LuckyLuke


2 Answers

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.

  • Expose your managed object context to other objects, typically as a property on your repository layer.
  • Have your repository layer initialise and return the objects for you. This would involve passing in an entity name and getting back a new managed object of the appropriate entity type or class.

If you find yourself fighting the frameworks and coming up with excessive abstractions, you're doing it wrong.

like image 197
jrturton Avatar answered Dec 29 '22 07:12

jrturton


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.

like image 32
mprivat Avatar answered Dec 29 '22 08:12

mprivat