Skip to main content

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.

Post a Comment

Popular posts from this blog

Lessons from my 9 Year Journey with DocuSign

After over 9 years at DocuSign I am taking on a new challenge.  It’s been phenomenal seeing the
company grow from from 25 to 2000 employees.  DocuSign has changed the way the people do business and I am proud of it.  The next chapter is going to be heading up software development at Tempo Automation - a 25 person startup that is changing the way people produce electronics.  While I am extremely excited about the future, this is a good time to reflect on my journey and share the things that contributed to the success and things that I will do differently next time around.
1: Focus on the Customer One of the key things that contributed to the success of DocuSign and my personal career is relentless focus on the customer success.  From the very beginning our CTO has taken meetings, listened and prioritized requests and feedback coming from customers.  People who could not be bothered by customer requests didn’t last long.  As a result over time our engineering team retained and reward…

Highly Effective Software Teams

A few weeks ago our Board of Directors asked me to present my assessment of the state of software.
 I was hired to organize and grow the software team and the directors wanted to know what kind of a team we needed to build.  I was hoping that I can just reference an article somewhere that would give me the answer, unfortunately I didn’t find anything suitable. During my research I did find some great material that will be helpful if your job is to put together a highly effective software team.
A highly effective software team has the following key characteristics: dependable, committed to shared goals, passionate about technology, respectful and compassionate.  These are not limited to technology industry, it can easily apply to finance, medicine, or sports as well.  Below is the summary and references that I found. Dependable If you are creating a software product, you need to deliver your software to your users.  Your users need to know that you are able to solve their problems on …

SDET / QA Engineer Interview Checklist

After interviewing and hiring hundreds of engineers over the past 12+  years I have come up with a few checklists.  I wanted to share one of those with you so you could conduct comprehensive interviews of QA Engineers for your team.

I use this checklist when I review incoming resumes and during the interview.  It keeps me from missing areas that ensure a good team and technology fit.  I hope you make good use of them.  If you think there are good questions or topics that I have missed - get in touch with me!


SDE/T or QA Engineer interview checklist from Mike Borozdin
If you like this checklist you might want to check out these posts:
Emotional Intelligence in Software Teams  and Good-bye manual tester, hello crowdsourcing!