4

I've been using Core Data for a while, but I just asked myself a question, I myself tend to always create some kind of local store class from which I manage the Core Data model, this would be a singleton class which has a reference to the managed object context, I have methods to create new managed objects, remove objects, save, etc... And my Managed Object subclasses are really only models.

But I've often worked with other peoples projects too and sometimes other developers tend to add more logic to the managed object subclasses in the form of class methods, and have a very simple or sometimes no Core Data "wrapper" class at all.

For example, I usually would do something like this:

User *me = [[MyDataStore getInstance] createUserWithName:@"Daniel"];

Whereas other rather have:

User *me = [User userWithName:@"Daniel"];

Obviously the latter is much nicer and in my opinion more human friendly, but one can end up with a lot of fragmented code, but one other hand, my solution means you have one very large file which isn't great once it gets past a certain length.

I wondered if others may share their point of view on this. Thanks.

Daniel
  • 23,129
  • 12
  • 109
  • 154

1 Answers1

4

From a MVC point-of-view placing logic code in the NSManagedObject subclass is the more correct thing to do. Personally, I find it a more logical thing to do, i.e. This code creates a new instance of User, so I will place it in the User class.

At a practical level I used to hate placing logic code in my NSManagedObject subclasses because if I modified my model it would all disappear, however I now use MoGenerator which looks after all of that and I don't have to worry about my custom logic being overridden.

Another thing I tend to try and leverage these days with CoreData is abstract entities. They are not only great for simplifying your model but also your custom logic, I mean it's basically just subclassing wrapped around CoreData.

Just my opinion and what works for me at the moment, Hope it helps someone, look forward to any other contributions!

Steffan
  • 200
  • 5
  • 2
    The problem of your custom code getting replaced by generated classes can be avoided by putting your custom code in a separate Objective C category. – Roger Jul 18 '12 at 07:13
  • Category sounds interesting. Thanks for your thoughts Steffan, maybe we can get some more opinions if we share this question on twitter or something, I really think it's an interesting question. – Daniel Jul 18 '12 at 14:37
  • Got bored of waiting for more opinions, they're not coming... you might as well get the reputation – Daniel Aug 03 '12 at 15:00