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!

Chief Collaboration Officer

When you search for the word “collaboration” on the Internet, the top hits are mostly software packages you can buy.  Software can facilitate collaboration, but it doesn’t make people collaborate on its own.

One of the key functions of a technical leader is to bring a team together, help people share ideas, and facilitate team members helping each other.  When a software leader overlooks this key function, you end up with a group of individual contributing engineers instead of a cohesive team.
Before we get into tactics, we should ask “Why is collaboration important for an engineering team?” 
It’s critical to examine your assumptions, so here are my reasons for why a group of engineers working on their own are worse than a team working together: Smart people learn from each other.Getting your plans and designs reviewed by other people allows you to leverage their experience and check your assumptions.Collaboration produces artifacts that stay after collaboration has taken place (such…

Hire Fast, Fire Fast? Not so Fast.

Silicon Valley is full of advice and it frequently comes from people who have little experience on the subject matter.  A popular topic surrounds hiring and terminations with the king catch phrase being: “Hire Fast, Fire Fast.”  To me, what that usually means is lack of diligence, thought, communication and courage.

When hiring people love going with their gut feel, often with disastrous results.  There is an obvious subject of diversity of thought, appearance and background.  When thinking “fast” you are probably hiring people like yourself because humans quickly react to people who they believe are in their tribe.

A startup that lacks the resources of a big company often becomes so desperate to get technical staff that when a decent candidate comes along, excitement ensues and the employer doesn't slow down to put them through a more rigorous hiring process.

I highly encourage technical founders and engineering executives to write out their precise hiring process.  Of course, y…