Sorting is an important feature in my app. I am using integers to represent the ordering sequence.
Items: A, B, D, E, H
Order number: 0, 1, 2, 3, 4
When I insert a new item "C", here's the outcome:
Items: A, B, C, D, E, H
Order number: 0, 1, 2, 3, 4, 5
Here's the write operation required on existing order numbers:
D: 2 -> 3
E: 3 -> 4
H: 4 -> 5
I wish to reduce the number of write operations because CoreData is pretty slow at writing. The problem becomes more significant when my users start to have a few thousand items in CoreData.
Here's my current workaround: leaving gaps between each order number. For instance:
Items: A, B, D, E, H
Order number: 0, 10, 20, 30, 40
When I insert a new item "C", here's the outcome:
Items: A, B, C, D, E, H
Order number: 0, 10, 11, 20, 30, 40
No write operations are required on existing order numbers.
Every 1 or 2 weeks, when my users close the app, I run background tasks to re-arrange the gaps between order numbers so that when users insert new items, fewer existing order numbers will be affected.
Items: A, B, C, D, E, H
Order number: 0, 10, 20, 30, 40, 50
Since sorting is pretty common, I was thinking some of you might have a better idea on how to reduce write operations on existing order numbers.
If you have a better idea, do you mind to share it with us? Thanks.
Managing a user-defined order is indeed pretty common. Core Data doesn't provide support for this topic, and so folks need to come up with their way. There are some discussions in Internet, and here is an example that may be helpful to you:
<https://begriffs.com/posts/2018-03-20-user-defined-order.html>
Best,
——
Ziqiao Chen
Worldwide Developer Relations.