Core Data – Simplified

1 min read

Every time I make an iOS app, I shy away from Core Data and end up storing data in a plist or sqlite. It's a senseless fear, but here's why I avoid it.

  1. CoreData barfs all over your AppDelegate
  2. It's somewhat difficult to add CoreData to an existing app
  3. The code for data access is a bit bloated

Tonight I took the plunge and found a great way to clean up your AppDelegate A LOT and simplify access to the data. All of the confusing context and coordinator stuff is completely abstracted away. You don't have to worry about initializing or accessing the manager because it's now static access to a singleton instance. Here's what my interface to Core Data looks like:

Here's what my interface looks like:

<p>@interface CD : NSObject {

<li><p>(void) save;</p>
<li><p>(NSMutableArray*) find:(Class)modelClass;</p>
<li><p>(NSMutableArray<em>) find:(Class)modelClass where:(NSPredicate</em>)filter;</p>
<li><p>(id) new:(Class)modelClass;</p>


Now I know CD is a strange class name, but my goal is painless access to data. So here are some code samples for using this interface:

<p>// Create a product</p>
<p>Product* product = [CD new:[Product class]];</p>
<p>product.Name = @"Fake Plastic Tree";</p>
<p>product.Price = 9.99;

// Save it</p>
<p>[CD save];</p>

//Fetch all products</p>
<p>NSArray* products = [CD find:[Product class]];</p>
<p> something with the products...</p>

What about the app delegate? Simple… now you just need ONE LINE in your AppDelegate (instead of literally hundreds).

<li>(void)applicationWillTerminate:(UIApplication *)application</li>
<p>// Do your normal stuff here

[CD save]; //this is the line you need to add</p>

So having used this for all of 10 minutes, I'm pretty happy with it. I don't know much about core data, so I might be missing something huge that blows this abstraction to pieces. I can tell you that it definitely works for a very simple 'Notes' app I just made.

I definitely need to add some more actions like 'delete' or 'count', but those should be trivial.

If you want the code, grab it from my Bendy Tree iOS Library on GitHub. To use it, just follow two steps:

  1. Add CD.h and CD.m to your project
  2. Change the path to your database inside CD.m (it currently says 'TestCoreData4')

I'm thinking of writing a tutorial on adding core data to a project, but for now Techotopia has a good tutorial on getting started.

Leave a Reply

Your email address will not be published. Required fields are marked *