Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

In this Swift Core Data Tutorial we will be covering; Fetched Request, NSManagedObjectModel, Persistent Store and Persistent Store Coordinator, Retrieving the Data Model, Managed Objects & Key Value Coding.

Swift 2 Core Data

This Swift Tutorial is the second installment of the Core Data Series. It is recommended that you have read through and understand the first part of this series.

Welcome back – I hope this means that you found the previous article useful. Ok, So let’s get straight into it.

Fetched Requests

A fetched request is not to be mistaken with Fetched Properties (A query that originates with a single Managed Object). Fetched Requests are more like a class method which will implement a canned query. So, for an example you might build a request named canFixComputer which returns a list of all your employees that have the technical ability to fix that pesky printer. When you run this, Core Data searched the persistent store to find all the current list of potential printer fixing employees. Through out this tutorial series, you will be creating many Core Data Fetch Requests, so do not worry now if you are not grasping it.


Configuration is basically a set of Core Data Entities and Different Configurations can contain the same entities. You use configurations to define what entities are stored in the Persistent Store. I can say that you probably wont ever use anything other than the default configuration.


This is a class that represents the Data Model in Memory. The template for this class will automatically create an instance of NSManagedObjectModel based on your Data Model. You will not typically access this directly but it’s a good idea to know what this is.

In the Navigation Pane (Left of your project) open the CoreDataApp group AppDelegate.Swift. In the Jump bar, click the last menu item which reads No Selection. This should show you the managedObjectModel In your Core Data Stack. Click this which will take you to the CoreDataApp.xcdatamodel file.

Now, using the Lazy construct in Swift, the managedObjectModelvariable is created of the type NSmanagedObjectModel when it is required. The variable will be initialized the first time it is called. So, You should see this in the file:

lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = NSBundle.mainBundle().URLForResource("CoreDataApp", withExtension: "momd")
    return NSManagedObjectModel(contentsOfURL: modelURL)

While it is creating the managedObjectModel it also creates (sets) the modelObject with the contents form the Data Model (CoreDataApp.momd). This is the line from the above code that does that:

let modelURL = NSBundle.mainBundle().URLForResource("CoreDataApp", withExtension: "momd")

For further information on the NSManagedObjectModel check out the Apple Documentation: NSManagedObjectModel Class Reference

The Persistent Store & Persistent Store Coordinator

Sometimes referred to as the Backing Store the Persistent Store is where Core Data will store the actual Data. It does this by using the SQLite Database that is by default stored in your iOS Devices documents folder as a persistent store. Now, this can be changed easily by editing a single line of code. I will show you how.

Before I do that here is a little warning: Do Not change the type of persistent store once you have posted your application to the App Store. If you must. You will need to look into Migrating Data for old Persistent Store.

Ok, so the Core Data Persistent Store is associated with a single Data Model and that defines the types of data that the Persistent Store can store.


It’s about time you knew a little secret, The Persistent Store is not actually represented by a Swift Class.. Shhh! Access is actually controlled by NSPersistentStoreCoordinator

Let us have a look at the method that returns the persistent store coordinator in your AppDelegate.Swift file. Make sure you select the function persistentStoreCoordinator from the function pop up menu, this is what you will get:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {

	 var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
	 let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDataApp.sqlite")
	 var error: NSError? = nil
	 var failureReason = "There was an error creating or loading the application's saved data." 
	 if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType,
		configuration: nil,
		URL: url,
		options: nil,
		error: &error) == nil {
			coordinator = nil
		 let dict = NSMutableDictionary()
		 dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
		 dict[NSLocalizedFailureReasonErrorKey] = failureReason
		 dict[NSUnderlyingErrorKey] = error
		 error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
		 NSLog("Unresolved error \(error), \(error!.userInfo)")

	 return coordinator

The first thing you can see is that this method uses lazy loading. Meaning that it will not instantiate the persistent store until it is first called. Then you will notice CoreDataApp.sqlite, This bit is where the method creates the file in your application sandbox.

The next thing I want to show you is the passed parameter: NSSQLiteStoreType, this constant tells Core Data to use the SQLite Database for the persistent store.

Managed Objects

So we mentioned entities before, those that define the structure of your data however they do not actually hold any data themselves. This is where managed objects comes in, These are the instances of the data. NSManagedObject will be the class or the subclass of every entity that you use in Core Data.

Managed Object Context

There is an object that acts sort of like a gateway between your entities and the rest of Core Data called Managed Object Context. This will keep track of any changes since the last time it was loaded. Here is an example; When you search for or load data you do that against a context, then when you want to commit those changes you save the context. It also handles everything you will need for the redo and undo features.

When you start an application you will mostly only be working with just one context however it’s very easy have more than one managed context. You can create nested managed object contexts. This means that the parent object store is another managed object context rather than a persistent data store.

Core Data Save on Terminate

Built into Core Data is a beautiful and nifty piece of code that will save just before it terminates. In your app delegate, find the piece of code applicationWillTerminate:

func applicationWillTerminate(application: UIApplication!) {
 // Called when the application is about to terminate. Save data if appropriate.
See also applicationDidEnterBackground:.
 // Saves changes in the application's managed object context before the application

Bear in mind that whilst this code is nifty and helpful, There will be times when you do not want this to run. For example, what happens when a user creates a new entity but then something shiny distracts them and thy quit your application before they have chance to add any information to the entity? This will save a blank managed objected to the persistent store. I might write another article talking about how to deal with this.

Key Value Coding

Just like Storing data to NSUserDefaults, NSManagedObject allows you to use the methods valueForKey and setValue(_:forkey:) for setting and retrieving attribute values. It also allows you to access additional methods for working with relationships.

Lets say that you have in your application an instance of NSManagedObject. You cold get this like:

var timeStamp = managedObject.valueForKey("timeStamp") as NSDate

This will return an instance of NSDate.. You could also set the value using setValue(_:forkey:) like so:

managedObject.setValue(NSDate(), forKey:"timeStamp")

Core Data Key Value Coding also allows you to iterate through object hierarchies easily using the valueForKeyPath:

var foodString = managedObject.valueForKeyPath("") as String


In This Swift 2 Core Data Tutorial I have covered the topics; Core Data Fetched Requests and Configurations, I have discussed the class NSManagedObjectModel that represents the Data Model Memory,Made you familiar with The Persistent Store & Persistent Store Coordinatoras well as Managed Objects and the Managed Object Context. I have shown you a nifty bit of code that terminates your Core Data Application and hopefully given you something to ponder in regards to validation of that dat and finally, I hope I have enlightened you with details about Key Value Coding

Part 3

That concludes the ‘Getting to grips with Core Data’ section of this Swift 2 Tutorial. In the following posts I am going to show you how to actually start using Core Data in your applications and hopefully show you just how useful and powerful it is.

The next article should be available soon, Sign up to the mailing list below so not to miss the next installment.

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly

Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.

Written by:

Nolan is a Mac OS X developer turned iOS engineer. At Twitter, formerly at Zappos and Cisco Systems. Married with two girls living in sunny Las Vegas.