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:
Entity — specifies the name of the things you are creating. If you are creating a Core Data structure to store different people, the entity would be “People”
Attributes — defines characteristics of an entity. If you again use the analogy of people, the attributes would be age, birthdate, etc.
Relationships — connections between multiple entities. They can be “to-many” or “to-one.” For example, an employer would have a “to-many” relationship with his or her employees whereas an employer would have a “to-one” relationship with his/her boss.
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:
Writing to Core Data
This function is how to save a “name” String attribute to an entity, “Person.”
Reading Core Data
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.