Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: To-Many Relationship ordered upon restart

When I restart my Core Data application with a to-many relationship my data (presented in NSTableView) is in random order. How do I keep it in that order in which the user left it before quitting the application?

Of course, I can sort the data in awakeFromNib but that does not give me the precise order the user used to arrange the data (e.g. he might rearrange rows manually).

The details of my document: What I have is an entity "Relationship" in a to-many relationship with an entity "Card" both managed by an NSArrayController. Card has 2 attributes, "number" (int) and "name" (String) displayed via Bindings in two columns of a NSTableView. Sorting is done by clicking on table headers.

How can I preserve the sort order?

like image 992
Core Avatar asked Dec 29 '22 09:12

Core


1 Answers

Core Data does not support ordered collections (like NSArray). This is to support things like fetching only a small subset of information without pulling in the whole store. This is why results are always given in an NSSet (an unordered collection).

The only way to preserve any kind of sort order is to add a property to your entity like "sortOrder" and make sure it's set to something valid. Then you can set your array controllers' sort descriptors to sort ascending by sortOrder. Similarly, if you're fetching manually using NSFetchRequest, you can set its sort descriptors as well.

Update for Lion (10.7)

If you're targeting 10.7 and above in your application, NSManagedObject now gives you ordered relationships. Use -mutableOrderedSetValueForKey: and -mutableOrderedSetValueForKey: to set and retrieve NSOrderedSets. Yay!

like image 75
Joshua Nozzi Avatar answered Jan 12 '23 21:01

Joshua Nozzi