Barcode Scanner iOS App Development iOS Swift Tutorial iOS8

Core Data Swift Tutorial

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.

If you get an error like this: Unable to load class named ‘Menu’ for the entity ‘Menu’. Class not found, using default NSManagedObject instead.

Swift classes are namespaced—they’re scoped to the module (typically, the project) they are compiled in. To use a Swift subclass of the NSManagedObject class with your Core Data model, prefix the class name in the Class field in the model entity inspector with the name of your module.


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

About the author


Backend/Infrastructure Engineer by Day. iOS Developer for the rest of the time.

  • Akash

    Hi Shrikar,

    Thanks for this article. This is really helpful for beginners.

    I am very new to iOS app development and have started with swift just recently.

    I am working on a basic idea right now and wondering how i can use core data and create a signup and sign in for my app.

    I have gone through lot of articles but never seemed to find a good one. Could you please help me by guiding me on how to use core data for a login module? It will be really helpful.

    Thanks in advance.

    • shrikar

      Are you trying to save login information in core data? If you do this the login information won’t be available from other devices . (Lets say the user installed the app on two devices). Normally you should keep login information available in cloud. (Something like parse). I think just for login information Core data is overkill. You could also use NSUserdefaults if you really want to store it locally.

      • Akash

        Thanks for that info Shrikar i didn’t know about that. Do you have any tutorials on how to store the login information in the cloud using swift?

        • shrikar

          Check the Yikyak tutorials. It shows how to interact with Parse.

          • Akash

            Thanks Shrikar. It was very helpful.

            Going off topic here. Through which resources did you manage to learn app development in swift? I have been going through the apple library and find that most of the delegates, api’s etc are still in objective-C and i have no clue about objective-C.

            So any help you could offer me and guide me in the right direction will be a life saver as i am working on building a enterprise level app in swift.

            Thanks in advance!!

  • muc2810

    Helle Shrikar, i’m looking for a tutorial about relationships in practice (One to many). You know wehre to find a good One?