A common question I see online about Core Data involves storing arrays. You have an array of a custom struct or class that you want to store in Core Data. Your initial instinct is to create an attribute for the array in your Core Data entity. But you discover that none of the available attribute types work. How do you store the array?
The Solution: Create a To-Many Relationship
There are two steps to storing an array of a custom struct or class in Core Data. The first step is to create a Core Data entity for your custom struct or class.
The second step is to add a to-many relationship in the Core Data entity where you want to store the array. The destination for the relationship is the entity you created for the custom struct or class. The to-many relationship holds the array items. Saving the main entity, the entity where you want to store the array, will save the array items.
Keep in mind that Core Data uses sets to store to-many relationships instead of arrays. Each item that Core Data stores must be unique. Each element of a set must also be unique, which is why Core Data uses sets.
A Simple Example
Let’s look at a simple example of creating a to-many relationship. Suppose you have a
Note entity and you want to store a list of each note’s tags. Start by creating a
Tag entity and adding the attributes you want a tag to have.
After creating the
Tag entity, select the
Note entity in Xcode’s data model editor and add a relationship. Name the relationship
tags. Choose Tag as the destination.
When you select the relationship, the data model inspector should be visible on the right side of the project window. Choose To Many from the Type menu. The relationship must be to-many to store a set (array) of items.
Select the Ordered checkbox if you need the relationship items to be in a specific order.
After creating the relationship each note has a list of tags. With the right controls in the app, you can add and remove tags. When you save a note Core Data also saves the tags.