Core Data introduction for new iOS programmers

Core Data is an object design, management, and persistence framework. It helps you manage the lifecycle of objects and object graphs. Core Data provides classes that are abstractions for common operations, including create, read, update, and delete.

.

This post was most recently updated in October 2013.

.

The Core Data Overview states the following important point:

Core Data is not an entry-level technology. It leverages many other Cocoa technologies and design patterns. You must understand [a number] of technologies and patterns before you can use Core Data effectively.

.

Is it difficult to learn? No, it is not. If you have the foundational knowledge and experience, you will find that Core Data is an elegant way to provide object lifecycle and persistence management.

.

Locating help documentation

Apple publishes a number of good-quality documents that we will use. We will also use the posted course notes (from this web site). To get started, I will suggest the following resources:

The document you are now reading (this document!)

Getting Started With Core Data

Technology Overview, and Core Data Basics, from the Core Data Programming Guide

Careful study of the “CD Simple” example app (it is well-commented)

Next week’s note(s)/post(s)

Careful study of next week’s Core Data example apps (which are well-commented)

.

Checkpoint: Where are we? What do we know?

At this point, your professor suggests that you pause and think about where you are in your learning path, and also about what you know about iOS programming. Specifically, think about the progress that you’ve made in three topic areas:

  1. Model objects (data)
  2. App styles
  3. Table views

.

Model objects (data):

  • You have been using model objects from the beginning of the course
  • Some model objects have been really simple – strings and so on
  • You then learned about and used arrays and dictionaries as model objects
  • And, you created (or learned to create) model objects of your own design

Now, you’re ready to use Core Data to manage and persist your model objects.

.

App styles:

  • Your first apps used a single view (+ view controller)
  • Then, you added the ability to show modal views on this style of app
  • We then introduced apps that support multiple views, in a tab bar, or navigation-based style

We will continue to use multiple views, typically in a navigation-based style, in apps that use Core Data.

.

Table views

  • In your first table view example, you saw that it used an array data source, and the array was created when the program launched
  • Then, we moved on to apps that used arrays that were persisted, typically in a plist
  • Finally, we were able to support multiple levels of navigation by using a carefully-structured dictionary as the data source, and dictionary methods that generated arrays

We will build on that understanding, by supporting table view editing operations, and by using Core Data as the persistent store.

.

Core Data introduction

Core Data is an object design, management, and persistence framework.

It enables developers to work with model objects (persons, cars, products, invoices, etc.) as first-class objects, without having to worry about a persistence scheme.

Core Data provides classes that are abstractions for common operations, including create, read, update, and delete. Operations can be performed on one object, or on a collection of objects. Relationships among or between objects are possible.

For example, a product manufacturer can make a number of products, or a musician can have a number of authored songs. In these scenarios:

  • Manufacturer object will have a collection property named Products; the collection is made up of Product objects.
  • A Musician object will have a collection property named Songs; the collection is made up of Song objects.

.

Some authors and reference resources like to compare Core Data concepts and operations with traditional database concepts and operations. We will NOT do that here.

Your professor insists that you MUST NOT strongly link and/or compare the two technologies, even though you are tempted to do so. Instead, you should learn the fundamental Core Data concepts, and if you have to make comparisons to aid your understanding, then you can do so on your own.

Comparing and/or equating Core Data and relational database management system technologies is a mistake.

The task below will be to provide a high-level overview of Core Data, so you can use it in the right way.

.

Data model

First, we start with a “data model”. It models the real-world entities that you want to work with. An entity has attributes and relationships. A “Student” entity, for example, would have attributes for name, student ID number, and so on. A student may have multiple addresses (e.g. mailing, residence, etc.), so we may also have an “Address” entity. There would be a relationship between “Student” and “Address”, maybe one-to-many. In a “Student” object, this relationship is realized as a property, perhaps named “Addresses”, which is a collection of “Address” objects.

So far, you may be thinking that an entity is the same as an object of our own design. Well, it’s almost the same. An object of your own design is a subclass of NSObject. An entity object is a subclass of NSManagedObject, and is usually known as a “managed object”. But they’re fairly similar. Both model something in real life.

.

Persistent store

Your objects are stored in a persistent store. The format and structure of the store shouldn’t really matter to you. (Does the format and structure of a “plist” matter to you? Didn’t think so.) The store is located in the app’s “Documents” directory, in a named file.

At this point, we’ve covered two components – the data model, and the persistent store. You understand both of them. Next, you’ll learn about a new concept.

.

Context

An app that uses Core Data has an object called a context (NSManagedObjectContext). It gets created when the app launches. The context is a “work area”. You can also think of it as a scratch pad or a white board.

What do we put in a context? One or more “managed objects”. In a well-designed app, the context object is available to all of the classes (typically view controllers etc.) that need to work with managed objects.

How do we add a managed object to a context? There are typically three ways:

  1. We fetch some objects from the persistent store; think of these as results from a query
  2. We modify one (or more) of these objects, perhaps by changing an attribute value
  3. We add a new object, which will (eventually) be persisted in the store

.

As a “work area”, the context is pretty useful. Fetch results are automatically placed in the context. We can ask the context to save changes. And, we can perform other typical data and object management operations.

.

Fetch

Let’s explore the task of fetching objects from the persistent store. Core Data has a “fetch” object (NSFetchRequest), which gets configured (by you) with fetch settings, typically in a view controller. For example, what entity do you want to fetch? Should all of the entity objects be fetched, or just a filtered subset? Should the fetch results be sorted/sequenced in some way?

At this point, you may be thinking that a fetch object is similar to a query. You would be correct.

A fetch object gets configured with the name of the entity that you want to fetch. Optionally, the fetch object can be configured with a predicate, to filter the selection. It can also be configured with one or more sort descriptors, to sequence the selection.

So, let’s assume that you have a configured fetch object. When you execute the fetch, a collection of managed objects is returned, and placed in the context. This collection can be used in any way you want – for example, you can extract a “name” attribute, so that you can display a list of names in the user interface.

What about editing or adding managed objects? Well, a fetch request that returns one object will deliver a managed object to the context. You can change one or more of its attributes, and when you save the context, the updated managed object is persisted. Alternatively, you can create a new managed object, configure its attributes, and again, save the context.

At this point, we hope that you “get” Core Data. There’s not much more to it. Sure, there’s syntax, coding patterns, and best practices, but they’re straightforward and fairly easy to follow.

.

Fetched results controller

One more thing… We often use Core Data when working with table views (UITableView). In this scenario, we always use an object called a “fetched results controller” (NSFetchedResultsController). The fetched results controller is an awesome chunk of functionality, providing state and behaviour that matches up very nicely to the needs of a table view.

.

Where can I see Core Data in an app?

The Xcode project templates that offer Core Data include the software objects needed for the Core Data stack in the app delegate. (You will soon learn that this approach is wrong.)

There are three objects in the stack:

  1. Managed object model
  2. Persistent store coordinator
  3. Managed object context

.

The managed object context is the most important and widely-used object in the stack. The managed object context, often referred to as simply “context”, is typically passed from the app delegate to the root view controller, in a simple navigation-based app. If you want to use Core Data, you simply need a reference to the context.

Where else do you see Core Data in an app? In a nav-based app that uses a table view, we use a fetched results controller. This object manages a collection of “managed objects”.

If a detail (view) controller needs a data-bearing property, the property’s type is NSManagedObject (or a subclass).

.

Getting started with Core Data in an app

In this course (and when you create your own iOS apps later), you will follow a pattern when using Core Data in an app. The code provided in the Xcode templates is not acceptable for use in this course.

Your professor is serious about this: Do NOT use the Core Data code in the Xcode project templates. Its quality is low, it isn’t easy-to-understand for new iOS programmers, and it’s scattered among a number of classes in your app. Bad, bad, bad.

.

The pattern relies on the following elements:

  • The Core Data stack is placed in its own class, and gets initialized at the proper time
  • The app continues to use a model object, as we have been accustomed to
  • The model object has public properties that expose data managed by Core Data

.

The diagram below shows the relationship among the app’s objects:

.

.

.

.

.

.

.

.

.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: