Core Data - Simplified

By Josh Wright on May 2011 in tips

 

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:

@interface CD : NSObject {

}

  • (void) save;

  • (NSMutableArray*) find:(Class)modelClass;

  • (NSMutableArray) find:(Class)modelClass where:(NSPredicate)filter;

  • (id) new:(Class)modelClass;

@end

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:

// Create a product

Product* product = [CD new:[Product class]];

product.Name = @"Fake Plastic Tree";

product.Price = 9.99;

// Save it

[CD save];

//Fetch all products

NSArray* products = [CD find:[Product class]];

...do something with the products...

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

  • (void)applicationWillTerminate:(UIApplication *)application

{

// Do your normal stuff here

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

}

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.