Blog Posts

Core Data : CRUD Operations

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:

  1. Persistent Container
  2. View Context from the Persistent Container
  3. Entity (NSEntityDescription object)
  4. FetchRequest (NSFetchRequest object)
  5. 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.

  1. NSEntityDescription: I created an entity description object for User
  2. NSFetchRequest: I created a fetch request object for User. Fetch requests will be used to fetch records from CoreData.
  3. 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!!!

« Previous Post

How does Apple push notifications work while we are not using the app!

Next Post »

Core Data: Entity Relationships

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.