nazbot
nazbot

Reputation: 1697

Best practice for core data function

What's the best design to use in an iPhone app that uses core data when you have several view controllers that make similar core data calls?

Currently I have an app which has several view controllers which all perform similar functions like adding objects to an entity, deleting an entity, etc. I figure there are a few ways to handle this:

  1. Each view controller has it's own addItem:blah class. Downside is this results in some copy-pasta between the classes

  2. Create a superclass which has the core data methods, and inherit from that class. Override where necessary

  3. Create a category so all instances of view controllers have those methods without needing to subclass

  4. Create a data manager singleton which can be called. Might be useful to have this so I can queue requests and do data management outside of each view controller. Downside is this feels like a bad idea in general

Upvotes: 4

Views: 398

Answers (1)

bandejapaisa
bandejapaisa

Reputation: 26972

CoreData and ViewControllers don't need to know about each other.

UIViewControllers are not traditional Controllers in the MVC world. They are more closely couple to Views - and I prefer to create them with this in mind,(most Apple example code has a lot of ModelController code - probably for simplicity of the examples).

I like to create ModelControllers and leave my ViewController managing my Views, and I give my ViewControllers an instance of my ModelController.

My ModelController will manage my Model, loading, editing, deleting etc... I still expose my Model classes to my ViewControllers, but Views NEVER leave the ViewController. You would never see a View in the ModelController.

The advantage of this is that if you later create an iPad app - your model and how it behaves is completely independent from your ViewControllers, so when you create some new UIViewControllers for your iPad app - you can plug in your ModelControllers.

Your ModelController could have a parent class that has your duplicate CRUD methods.

Alternatively....

A library called MagicalRecord https://github.com/magicalpanda/MagicalRecord adds the Active Record pattern to NSManagedObjects.

Upvotes: 4

Related Questions