What if I want to integrate CoreData later?
I actually use Realm more often. But don’t you feel like this sometimes? What if I want to use Core Data later? What if a cool new Core Data feature comes out and my project needs to be migrated? So I did some research and found it to be very easy. However, other blogs did not explain it as easily as I did, and there were too many additional explanations, so I couldn’t get the gist of it.
What we usually do when using CoreData
Oh, I forgot to check “Use Core Data”!
Don’t worry. It’s really easy to integrate.
1) Create Data Model
2) Add Core Data Stack Code
Wow. This really looks similar when you create a project with “Use Core Data” marked. That’s right. Because what we need is persistentContainer
and saveContext()
method.
You can create your own class or attach this code snippet on AppDelegate depending on your taste. I personally added on AppDelegate.swift.
#Note!!!
let container = NSPersistentContainer(name: “Posts”)
Posts is the database name we created!!! It should match when instantiating NSPersistentContainer
3) Define your model in xcdatamodel (Optional)
Integration part is already finished at Step 2, but if you want to follow along, read more!
- Go to Posts.xcdatamodel
(1) Create Entity
(2) Define your own model
I made three properties. If I describe it with code, it would look like this.
// You don't need to write this code!!!
// It's already auto-generated by CoreData
// It's just an example to make you understand.
class Post {
var title: String
var content: String
var created: Date
}
#Warning!
You don’t need to write any code to generate model.
“CoreData auto-generates model class for you”.
4) CRUD (Optional)
CRUD stands for Create, Read, Update, Delete. It’s a common acronym for developers. This is the concept that you will learn first when you handle any kind of databases.
(1) Create
As you can see, we need persistent context and saveContext() to use CoreData.
(2) READ
We need only persistentContainer to read data.
(3) Update
Call saveContext() after you changed model class.
(4) Delete
After you deleted model object, you should call saveContext()
5) CoreData Common Workflow
- What you need is persistentContainer and saveContext().
- When you load data and need built-in functionalities, you need to obtain context, which can be accessed by persistentContainer.
- When you changed model object, always call saveContext()
Conclusion
It’s really not that hard. What you need is just persistentContainer and saveContext() with xcdatamodel files you create. So, don’t worry if you didn’t enable CoreData when creating a project.
Check this repository!