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

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!

There are Only Two Ways to Treat Your Team

There are only two ways to treat your team: take care of them or let them go.  Early in my management career there have been times when someone has been underperforming on the team.  Before I knew better I let my emotions get the best of me: I’d give them the cold shoulder, avoid including them in conversations and look like I was upset with them. Thankfully with some good mentorship I came up with a simple rule: we are helping each other or you are off the team.

One of the biggest mistakes that folks make a lot of times is letting people linger on for too long.  Hiring good engineers is hard and getting new folks up to speed is hard.  You feel like you are going to miss your product delivery plan if you let someone go.

Letting folks linger when you are unhappy with each other creates a toxic environment.  This toxic environment is generally contagious and brings the entire organization down.  Of course you can’t have a constant state of euphoria on your team, but if a productive and…

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 …