Core Data Swift Tutorial

Shrikar Archak / February 08, 2015

4 min read

Core Data

Core Data Features

Core Data framework provides a simple way of maintaining the life cycle of the objects and object graph management including persistence. Here are some of the main features of Core Data.

  • Relationship maintenance
  • Core Data manage change propagation and maintain consistency of relationships among objects
  • Provides mechanism for schema migration.
  • Automatic support for storing objects in external data repositories
  • Sophisticated merge policies and conflict resolution

I didn't find any good tutorials to use Core Data in Swift. So thought of building an app to interact with Core Data.

Core Data Terminologies

Managed Object Context

We can think of managed object context as a staging area for all the objects where modifications to the objects happen. The data store in the managed object context is not persisted in the persistent store.

We need to explicitly call the save on the context to persist the data.

Managed Objects

Model objects that tie into in the Core Data framework are known as managed objects. All managed objects must be registered with a managed object context. You add objects to the graph and remove objects from the graph using the context.

Fetch Requests

To retrieve data using a managed object context, you create a fetch request. A fetch request has three parts.

  • It should what type of entity data it should fetch
  • It may also contain a predicate object that specifies conditions that objects must match
  • An array of sort descriptor objects that specifies the order in which the objects should appear. Like you can specify that you want the latest created objects to appear first or sort by a name parameter withing the model

Persistent Stores

A given persistent object store is associated with a single file or other external data store and is ultimately responsible for mapping between data in that store and corresponding objects in a managed object context.


If you are using core data with UITableView then this is the most useful class for that purpose. You use a fetched results controller to efficiently manage the results returned from a Core Data fetch request to provide data for a UITableView object.

You configure a fetch results controller using a fetch request that specifies the entity, an array containing at least one sort ordering, and optionally a filter predicate. The fetched results controller efficiently analyzes the result of the fetch request and computes all the information about sections in the result set. It also computes all the information for the index based on the result set.

In addition, fetched results controllers provide the following features:

Optionally monitor changes to objects in the associated managed object context and report changes in the results set to its delegate. We need to implement NSFetchedResultsControllerDelegate if we want to be notified when there are changes to the managed object context.

Core Data
import Foundation
import CoreData

class Menu: NSManagedObject {

    @NSManaged var menuText: String
    @NSManaged var createdAt: NSDate


Creating a new object.

func insertNewMenu(menuText : String){
   let menuEntry = NSEntityDescription.insertNewObjectForEntityForName("Menu", inManagedObjectContext: managedObjectContext!) as Menu
   menuEntry.menuText = menuText
   menuEntry.createdAt = NSDate()

NSFetchedResultsController code

Use this code in the TableViewController code

var fetchedResultsController: NSFetchedResultsController {
   if _fetchedResultsController != nil {
       return _fetchedResultsController!
   let fRequest = fetchRequest()
   let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fRequest, managedObjectContext: coreDataStack.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)

   aFetchedResultsController.delegate = self
   _fetchedResultsController = aFetchedResultsController

   var error: NSError? = nil
   /* Perform initial fetch */
   if !_fetchedResultsController!.performFetch(&error) {

   return _fetchedResultsController!

var _fetchedResultsController: NSFetchedResultsController? = nil

NSFetchRequest Code

For Creating a fetch request. Change Menu to whatever entity you have.

func fetchRequest() -> NSFetchRequest {
   let fetchRequest = NSFetchRequest(entityName: "Menu")
   // Set the batch size to a suitable number.
   fetchRequest.fetchBatchSize = 20
   // Edit the sort key as appropriate.
   let sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: false)
   fetchRequest.sortDescriptors = [sortDescriptor]
   return fetchRequest

Shrikar Archak


IndieHacker and Software Developer. Getting started to build in public.Tweet me @shrikar84 for any collaboration opportunity or brainstorming.


Subscribe to the newsletter

Get notified when new content or topic is released.

You won't receive any spam! ✌️