Software, Team and Strategy

Mike Borozdin - Kubernetes @ Google. Previously: Dir of Eng @ DocuSign, Lead @ Microsoft. I help companies focus and engineers grow.

Friday, June 13, 2014

4 Page Guide to Core Data

Quick Guide: How to Use Core Data for Your Next iOS Project

In my last iOS project, I decided to use Core Data by Apple. My goal was simple: to store some data in my iOS app and be able to perform CRUD (Create, Read, Update, Delete) operations.
While there are long guides on how to properly use Core Data, I thought none of them gave me the information I needed in a concise and accessible way. If you are exploring Core Data for your project, and you have some background knowledge of database interfaces, I hope this 4 page guide gets your application up and running in no time.

Why should I use Core Data?

There are other ways to store data on your iOS app and some have a variety of great features like Parse.  My task was to store data about the application with minimal dependencies.  I also wanted to be able to handle undo/redo in my app, which CoreData supports out of the box.  For a full set of Core Data capabilities, visit Apple’s page: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdTechnologyOverview.html 

How do I get started with Core Data in my project?

If you are starting a new project – you can select support for Core Data in the project template selection.  I did the Master Detail application and the wizard created everything I needed including wiring up the fetching of the records into the master view.

Suppose you want to import Core Data into an existing project.  There is a great discussion about it on StackOverflow: http://stackoverflow.com/questions/2032818/adding-core-data-to-existing-iphone-project 

In short you will need to do the following things:
1) Add the Framework by including the binaries and the headers
2) Add a Data Model file
3) Update the App Delegate
4) Update ViewControllers or other objects that you want to be able to use the data.
The stack overflow discussion has the code for you to copy.

How do I define the data?

When you click on the Data Model file you can add entities and their attributes.  This is similar to laying out the tables in graphical database modeling tools.  Attributes can be of various types.  Entities can have relationships.  There are other more advanced things you can do with Core Data, which you can probably add once you get a hang of the basics.

Productivity tip – create wrapper classes for your data

I wanted to work with Objective-C classes as much as I could.   Thankfully, XCode can generate those for you very quickly.  Just create a new file and then select the Core Data tab where you can generate a NSManagedObject subclass.   After you walk through the wizard, you will have classes that map to your entities.

Create

Creating a new entity in your database with the setup that you have by now should be pretty simple.    You need to do it in a place where you have access to the managed object context (moc below).   In the code snippet below you can see that the steps are pretty easy:
1) Insert + Create a new object into the context.
2) Given the new object set the properties on it.
3) Tell the managed object context to save everything.

    Invoice *newInvoice = [NSEntityDescription                
                             insertNewObjectForEntityForName:@"Invoice"
                             inManagedObjectContext:self.moc];
    newInvoice.title = @"Invoice 101",;
   
    NSError *error = nil;
    if (![self.moc save:&error]) {
       //handle error

    }

Read

To get your entities from the database you need to follow the following steps:
1) Create an entity description for the entity name with the managed object context ( moc below ).
2) Create a fetch request.
3) Set the entity description that you want to fetch.
4) Execute the request and given that there is no error you should have an array of objects.
5) You can then go through the array and use the wrapper class to get the attributes of the entity.

    NSEntityDescription *entityDescription = [NSEntityDescription
                             entityForName:@"Invoice"
                             inManagedObjectContext:self.moc];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *array = [self.moc executeFetchRequest:request error:&error];


    for (id object in array) {
        Invoice* invoice = object;

    }    

There are many other flags and attributes you can use to filter and sort the data, but the example above gets you to your data array the fastest.  In a ViewController you might consider using a NSFetchedResultsController if you want something that plays nice with table view controller.

Update

Updates to existing objects are even easier.  Given that you have fetched a number of objects and your UI allows the user to update one of them you can then just change the values in that object and then call save on NSManagedObjectContext.  Here is a simple example that builds on the insert and select above.

    Invoice* invoice = [array objectAtIndex:0];
    invoice.title = @"Updated Invoice 112";
    if (![self.moc save:&error]) {
       //handle error

    }

Delete

Delete is even easier.  You can mark the object for deletion by calling deleteObject on NSManagedObjectContext and then calling the save to commit the changes to the database.

Conclusion

When I originally found Core Data and its corresponding 179 page guide, I thought it would be really complicated to work with, but it turns out that Core Data is straightforward to start using for basic CRUD operations for an iOS project. As your application and your problem space grows and you begin using more advanced features of the framework

PS: if you liked this post you might like to read my other hands on posts like the one on Heroku and the general thoughts about staying hands on while advancing up the management ranks.
PPS: you can find me on twitter @mikebz.

Labels: , , , ,