iOS Core Data – batch delete duplicates

batch-deleteBatch deletes are fast and efficient for deleting Core Data entities when using an SQLite persistent store. They provide far better performance than deleting specific NSManagedObjects because batch delete operations are performed in the persistent store (at SQL level). Since the changes are reflected in the persistent store, they are not reflected on objects that are currently in memory.

After the batch delete is performed, the deleted objects need to be removed from memory also. A convenient way to update the in-memory objects of certain NSManagedObjectContext is using the refreshAllObjects method.

I’m using NSExpressionDescription since I’m not fetching an attribute or relationship of Product NSManagedObject. NSExpressionDescription can be used to describe a column to be returned from a fetch e.g. upper(attribute) or max(attribute), or in this case NSManagedObjectID. I’m grouping Product objects by productId. Using the predicate I’m specifying which object to keep, otherwise it might be a random object. I’m using this because e.g. different server API calls might return light or full object description that can be ingested into duplicate objects so you might have objects with more and less information. You likely want to keep the object with most data so this is specified in the predicate. Once the fetch request for objects to keep is configured, it is straightforward to compose a fetch request that is going to use the returned NSManagedObjectIDs of objects to keep in order to fetch all other objects i.e. duplicates.

Using the above duplicates fetch request it’s simple to create and execute the batch delete as seen below.

For more info and code sample check out my GitHub repo: https://github.com/lukagabric/BatchDeleteExample

If you liked this blog post I’d appreciate if you followed me on Twitter

Related Post

Remember to share...Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *