Skip to content

Category: Core Data

Order your Core Data entities the right way for maximum speed

One of the earliest things you learn about Core Data is that it doesn’t support ordered entities out of the box. Sometimes you can have an ordered relationship, but the minute you try and move that database to iCloud, you find that ordered relationships aren’t supported. Long story short: if you want to order your entities, then you need to create an index attribute that allows you to sort your entities yourself.

So you do the natural thing: create your index attribute as an Int, and then assign each in order: 1, 2, 3…

This is fine if the data doesn’t change, but if this is data the user can add to and reorder, what if they want to move element 3 between 1 and 2? It means you need to change 2 entities in addition to adding the new one. What if there are 500 entities, and the user wants to insert a new first element. 500 entities to change because the user moved a single entity?!

There must be a way to insert and reorder IDs that avoids all of this rewriting, right?

Thankfully there are a couple of techniques you can use that will almost completely eliminate the need to rewrite a huge number of entities every time you need to insert or rearrange entities. Let’s talk about them now.