← Back to Blog

Swift Core Data Basics: Storing App Data

coding
mobile
tutorial

By Kevin Hou

4 minute read

Core Data is an important component of many complex apps. An app’s lifecycle is a complicated topic, but data management can be articulated as such: When you kill an app (or shut down your phone), any data that isn’t designed to persist between sessions will be deleted. The solution is to either use persist data with NSUserDefaults or by using Apple’s Core Data. Again, Core Data is another incredibly complex topic, but this blog post should give you the necessary tools to start using it.

Setting Up Core Data

First, create a page based application and check the Core Data options. This will initialize a Core Data stack in the AppDelegate.swift file as well as create a .xcdatamodeld file in your project’s parent folder. The heart of Core Data lives in this .xcdatamodeld file. Selecting the file will expose a powerful Xcode editor for creating entity types that you can use to store data between app sessions. You can double click the entity name to change its label and add attributes, relationships, and fetched properties. Here’s an overview of these three vocabulary words:

The Core Data editor is relatively intuitive. Create an entity by pressing the “Add Entity” button in the bottom left and add attributes and relationships using the corresponding plus buttons. Like objects and classes, the entity name is uppercase whereas attributes are camel case.

Saving to Core Data

Import the CoreData module in whichever file your view controller lives in. Core Data objects are returned as a variety of object types, but the most basic is a “NSManagedObject.” Below is an example of how you would retrieve Core Data:

1// Entity: “Person” 2// Attribute: “name” 3var people = [NSManagedObject]() 4let person = people[i] 5let name = person.valueForKey("name") as? String // Xcode doesn’t know what type the value is 6

Writing to Core Data

This function is how to save a “name” String attribute to an entity, “Person.”

1func saveName(name: String) { 2 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // Access the app delegate in order to save to Core Data 3 let managedContext = appDelegate.managedObjectContext // Get managed object context 4 5 let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext) // Identify the entity 6 7 // Create a new instance of Core Data and store temporary on the managedContext 8 let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) 9 10 person.setValue(name, forKey: "name") // Set an attribute 11 12 do { 13 try managedContext.save() // Save the temporary data to Core Data 14 people.append(person) // Also add to local data so don't have to be constantly reading Core Data 15 } catch let error as NSError { 16 print("Could not save \(error), \(error.userInfo)") 17 } 18} 19

Reading Core Data

1let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // Get App Delegate 2let managedContext = appDelegate.managedObjectContext // Get the managed object context 3 4let fetchRequest = NSFetchRequest(entityName: "Person") // Get the entity objects from Core Data 5 6do { 7 let results = try managedContext.executeFetchRequest(fetchRequest) // Fetch results 8 people = results as! [NSManagedObject] // Store locally 9} catch let error as NSError { // Catch errors 10 print("Could not fetch \(error), \(error.userInfo)") 11} 12

Those are the basics to Core Data! This is obviously a very simple example, but it’s integral to anyone learning to build iOS apps.