5 Performance Improvements for Core Data in iOS Apps

Reach for quality!

Steven Curtis
5 min readMar 20

--

Photo by Reign Abarintos on Unsplash

My favourite way of persisting data is with Core Data.

It’s an integrated Apple Framework — so don’t worry about your third-party stuff here. I like to write a Core Data Manager that is testable and can even be mocked.

However, where are the performance improvements that can make your App, well, usable?

They’re right below!

Difficulty: Beginner | Easy | Normal | Challenging

Terminology

Core Data: A framework that allows you to manage the model layer objects in your application. Core Data does this by being an object graph management and persistence framework.

Prerequisites:

Stop using the viewContext!

That sounds a little bit strong. However, in my example Core Data Manager I have hard-baked the viewContext. Now you should only read on the viewContext from the main thread, and you should write using persistentContainer.newBackgroundContext().

This prevents saving on the main thread, while stops the user having to wait around for the background thread (but if you are only shifting a small amount of data this will not be a concern).

Only save if the managedObjectContext.hasChanges

You can check if your managed Object context actually has any changes before engaging in the heavyweight action.

if self.managedObjectContext.hasChanges {
// save your work
}

This is surely the least you can do?

Test with NSInMemoryStoreType

If not you can inject a managedObjectContext with an NSInMemoryStoreType with something like the following:

--

--