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!

Pull Requests and Code Reviews

Software development involves a great deal of collaboration.  One of the most basic blocks of collaboration on a software development team is a code review.  There have been many different ways of doing code reviews over time, some of this has been dictated by the tools available.  Git and online source collaboration tools created a set of best practices that are worthwhile of adopting on any team.

About a month ago I have looked at various articles about how to best create a Pull Request (PR) and do a code review and the attached presentation is the result of this research.  The presentation can help you guide your team and develop a set of collaboration practices that works for your particular situation.

It’s good to start out with why to seek a code review.  Having clarity about your intentions helps you guide the person helping you with code reviews and also to manage your expectations about you can get out of the code review.  The reasons for seeking a code review are generally …

Why you should take the software job in San Francisco (or not).

Silicon Valley is an iconic place for technology.  Many people say this is the place for the “best and the brightest.”. Apple, Google, Facebook, Salesforce, Twitter and other top companies draw a lot of talent form all over the world and the largest chunk of VC capital goes to companies in the Bay Area, so it seems like moving here is a no brainer!

The real situation is actually not that simple, I believe there are three scenarios where it makes sense, but in many cases living in the Bay yields disappointing results.  The cost of living, housing situation, homeless catastrophe make places like San Francisco a lot less appealing to a lot of people.  So in what situations does it make sense to move to SF?

Startup founder raising millions There are many places to be a startup founder, but if you are looking to raise capital the largest pool of VC money is in the Bay Area.  There is an established network, events and conferences which give founders an opportunity to pitch more people th…