Introduction

This is the fourth part of the series CoreData: CRUD With Concurrency In Swift: DELETE.

If you didn’t read the first part, I would suggest you to read it since I introduced this series. You can find the second part here and the third one here.

In this article we are going to learn how to delete the data with CoreData using background queues—to avoid blocking the main queue.

CoreData provides mainly two ways to do it: Either using a NSManagedObject or NSBatchDeleteRequest.

Happy Reading!

Contents

Using NSManagedObject

Let’s consider that our App allows the user to delete a specific Dog. In this scenario, we would have a NSManagedObject object to delete.

Once we have a specific NSManagedObject, we can delete it very easily. Let’s see in the examples below:

iOS 8+

iOS 10+

When we delete a NSManagedObject object, then we must save these changes manually—like in the examples above—to update our database.

Using NSBatchDeleteRequest

The approach of Using NSManagedObject has a problem. If we want to delete all the dogs in our system with a specific name, for example all the Max dogs, we should create a NSManagedObject per dog to delete and then delete all of them manually.

Fortunately, Apple introduced, in ios 9, a better way to delete all the entries which satisfy the criteria of a specific predicate: NSBatchDeleteRequest.

It’s very similar to NSBatchUpdateRequest, which we have seen in the previous part of this series.

For the sake of explanation, let’s consider that we want to delete all the Dogs with the name Max. Let’s see how to do it using NSBatchDeleteRequest:

iOS 9+

iOS 10+

As we saw in these examples, there are three main points to delete our data:

  1. Create a request to filter the entity to delete.
  2. Execute the request with resultType set to resultTypeObjectIDs, since we need just the IDs of the objects deleted.
  3. Update the main context.

Note

If we want to support ios 8, then we should fetch and delete all the entries manually like this:

We used the fetch property includesPropertyValues which lets return just the objectIDs of the fetched elements. To delete an object we don’t need all its property, its objectID is enough.

Conclusion

We’ve just finished our journey in the CoreData concurrency world. Now, we are ready to ship faster Apps using CoreData in background queues. Concurrency is a scary world, fortunately CoreData is able to provide us an easy way to manage different queues without hurting ourself.