Adding The Model File
To begin we need to create a new data model file in our app. This is the same process as adding a regular swift file but instead we select a Core Data file. The default name is "Model" which I works for me, but it can be named whatever we want.
Within the new model file there are three main sections.
Entities - these give us a way to describe the classes of the data model. They will eventually be turned into swift classes by Xcode.
Fetch Requests - part of the
NSFetchRequest
class which makes up part of the the Core Data Stack can also be added to the model directly. A lot of programmers create them separately in code to keep the model as simple as possible.Configurations - this is a very powerful tool that allows us to create several different Stores. It handles which Store each Entity belongs to. A common multi-store paradigm is to have a SQL Store and an in memory Store. The in memory Store acting as a cache for objects that might live in the cloud.
Adding Entities
To add a new Entity all we have to do is click the button in the bottom left of the editor.
From there we need to add attributes of what we would like to save, once Xcode turns the Entity into a class all of the attributes become properties. In the case of a SQL Store these will end up being the names of the columns in the database.
To add a new attribute we click the little + icon and specify the attribute name and data type.
Further options for attributes can be configured in the inspector, such as minimum values or if the attribute should be optional.
One notable option is Transient
which indicates that the attribute will not be saved in Core Data.
Core Data will make sure that an object will never be saved that does not meet all of the requirements of it's attributes.