Beginner’s Guide to Core Data in Swift 4
It doesn’t have to be that hard
Last update on May 12th, 2017
I promised with my readers that the next article was going to be about CoreData
. So, this article is written for anyone who has never used Core Data
before.
Why Core Data?
Core Data is just a framework like UIKit. It is used to manage data/models. There are a couple of notable built-in features such as 1. change tracking of data, 2. undo and redo to data 3. Filtering 4. Save on to the disk. 5. Partial loading unlike UserDefaults
It is true that there are other frameworks built by non-Apple engineers such as Realm which acts like Core Data
and feel free to use that instead. I’m not going to talk about pros and cons in this article. (I also don’t know much of it)
What I think you will learn
This is a starter’s guide. I’m not going to dive in deeply. However, you will be able to save, retrieve, delete data from the disk. I assume you are aware of the meaning of delegate
, optionals
and how to use UITableView
.
If you are not comfortable with OOP, delegate, optionals, and error handling, you might want to join Learn Swift with Bob.
UI
Every starter project begins with creating a decent UI first and, of course, a to-do app. There are two view controllers. The first is only comprised of a table and you can add tasks from the second view controller. Once you click the “Add Task” button on the second viewcontroller, it will pop back to the first view controller and you will see the item listed.
I’m not going to talk about how to implement the UI in Storyboard. I posted source code for you on the bottom of this article, so feel free to just read through this tutorial first and then play around with it.
Let’s Get Real
When you first create a project, you have to specifically mention that you are going to use Core Data
Once you do, you will see a weird looking file name called .xcdatamodeled
Don’t worry. It’s just like a spreadsheet file. Click on it, and you will see Entities
and Attributes
I’ve added Task
under Entities and name
under Attributes. Imagine, Entities are like an array of humans and attributes are legs, hands, fingers, and so on.
So, let’s start off with saving data on the second viewcontroller which I call it as AddTaskViewController
.
I have decided to migrated from Medium to the personal blog. The rest of the content about Core Data can be found here.