Master data: many relationships ordered after restart

When I restart the Core Data application with many relationships, my data (represented in NSTableView) is in random order. How to save it in the order in which the user left it before exiting the application?

Of course, I can sort the data in awakeFromNib , but this does not give me the exact order that the user used to organize the data (for example, he could manually change the lines).

Details of my document: what I have is a Relationship entity, in conjunction with a Card entity, which is managed by NSArrayController. The card has 2 attributes, "number" (int) and "name" (String), displayed through Bindings in two NSTableView columns. Sorting is done by clicking on the table headers.

How to keep sort order?

+4
source share
1 answer

Core Data does not support ordered collections (e.g. NSArray). This should support things like fetching a small subset of information without involving the entire store. This is why results are always set in NSSet (unordered collection).

The only way to preserve any sort order is to add a property to your entity, such as sortOrder, and make sure that it is set to something real. You can then configure the sort control descriptors of the array controllers to sort in ascending order through sortOrder. Similarly, if you manually load NSFetchRequest, you can also set sort descriptors.

Update for the Lion (10.7)

If you target 10.7 or higher in your application, NSManagedObject now gives you an ordered relationship. Use -mutableOrderedSetValueForKey: and -mutableOrderedSetValueForKey: to set and get NSOrderedSets. Hurrah!

+10
source

All Articles