There are 3 main stages of Core Data: Modeling, Saving & Fetching. We start by building a Data Model with the Entities we want to persist. Then we save the instances of those entities that are in our Managed Object Context. Then we can fetch those saved instances (Managed Objects) from our context. Optionally, we can filter and sort those fetched objects.

NOTE: This post assumes you set up the Core Data stack already. If you haven’t, it might be helpful to look at the post on Apple’s Core Data Boilerplate code.

MODELING

Image for post
Image for post

Modeling is the first and most important part…


So far, after making Entities in our Data Model Editor, we instantiate NSManagedObjects using the Entity’s EntityDescription. Now that’s fine and dandy but there are some issues with this approach.

First off, when we want to set the attributes of the Managed Object, we can’t use dot syntax like we would when we set the properties of regular objects. Dot syntax is way cleaner and way more convenient than the setValue:forKey: method we’ve been using. Here are two reason why you would want to use dot syntax instead

  1. When we use the value-key way of setting our attributes, we can…

We can learn a lot about Core Data by looking at Apple’s boilerplate code when we have Core Data checked in our project. So let’s have a looksie.

Let’s start by making a new project and checking Core Data.

Image for post
Image for post
Don’t Forget to check Core Data

Let’s have a look at the file structure


Learning Core Data can be a bit of a doozy with all the technical sounding jargon. Before jumping into how to use Core Data, getting to know a little background of the players in the framework can prove to be beneficial.

Image for post
Image for post
Apple’s Diagram on the Core Data Stack

If this diagram doesn’t make sense, don’t worry about. We’re about to go through this stack in detail.

  1. Entity Description ( NSEntityDescription ) TLDR: It’s the Core Data equivalent to a Class Description You can think of an entity description as a class description. Just like how you would make a Class for Dog and give it name, weight…

Magfurul Abeer

Mobile Developer. Super geek and knowledge junkie with hopeless plans to one day learn everything under the sun

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store