Core Data : CRUD Operations
Core Data CRUD Operations
In the previous article Core Data : Managed Object Model, we learned about Managed Object Model, how to create entities, their attributes, and relationship between entities.
In this article, we will learn the CRUD operations i.e. Create, Read, Update and Delete records from the Core Data Entity. We will use the User entity created in previous article.
To deal with Core Data we need the following objects:
- Persistent Container
- View Context from the Persistent Container
- Entity (NSEntityDescription object)
- FetchRequest (NSFetchRequest object)
- Predicate (NSPredicate object)
I created a constant.swift class where I created objects that were used in multiple locations. I’m going to use this class to get viewcontext.
Create/Update record in Entity
The following function can be used to create a new record of a user or update an existing record:
First of all, we will check if there is an existing record in the table. We will create a new record in case there is no existing record, else the existing record will be updated.
- NSEntityDescription: I created an entity description object for User
- NSFetchRequest: I created a fetch request object for User. Fetch requests will be used to fetch records from CoreData.
- NSPredicate: is used to get particular records from the Core Data. We can apply the conditions. For example, in this case, we have checked for the uniqueUID of the user to get a particular record.
Read/Fetch Records
The following function will be used to get all the records from the User Entity:
Delete Records
We need the entity record to be deleted to delete a record from an entity. Then we call the delete function of ViewContext and pass the object to be deleted.
Whenever we make any changes to the records (add/edit/delete) in an entity, we need to call the save() function on the ViewContext. The save() function saves the changes to the persistent store.
The following function will be used to get all the records from the User Entity:
In this article, we have learned how to add, edit, delete and fetch records from CoreData Entities.
Feel free to contact me for any further clarification on the subject matter.
Stay Tuned: My next article is going to talk about CoreData entity relationships.
If you enjoyed this blog post, share it with your friends!
Cheers!!!