Core Data

Core Data

For some reason I find that the data I have entered gets displayed in a different order sometimes after closing the file and re-opening it.

Its not obvious how to set the sort order anywhere or how one would allow the user to re-order a list and make sure it gets saved and can be displayed in the same order next time. Suggestions on the best way of doing this would be useful.

The first part, how to set a sort order is covered in chapter 4, NSSortDescriptor (p 70). It includes code, and it is explained very well, but there’s no help with how it is folded into the rest of the application.

I’ve spent a few hours trying to figure this out, what I have now is this:

Core Data does not store the data in an ordered form. That is why relationships are sets and not arrays. The data and the persistent store do not care about their order. Order is most important in the display and therefore should be solved in the display.

Assuming that you are displaying the data in a table view, then you can configure sort descriptors on the tableview itself. If you are loading the data into a drop down or other UI element then I recommend performing the sort just before you return the data back to the UI.

Giving the user the ability to change the sort is also normally performed at the table view. By configuring a sort descriptor for the table column the user can click on the header and get sorting “for free”.