views:

46

answers:

2

I have an NSMutableArray which has about 18 objects. They are in a specific order that I want. I have to add these objects into an NSSet to be saved in Core Data.

But, once I pull them out of the NSSet using [myObject.items allObjects] it does not keep the original order that I added the objects as. How can I keep the order that I want, I don't want to have to resort them.

+1  A: 

If you don't want to sort them you can add a property (e.g. int indexInList) to the objects which stands for the position in the list.

But sorting the list in respect to a property of the objects would be very easy too with

- (void)sortUsingSelector:(SEL)comparator
- (void)sortUsingDescriptors:(NSArray *)sortDescriptors 
...
brutella
Ok, but my confusion comes from why it is automatically not keeping my sort order when I add an object to the NSSet.
Nic Hubbard
Sets don't have an order. That's a fundamental property of a set.
Ken Aspeslagh
Because of this you can't have one object twice in a set - in an array it's possible!
brutella
+1  A: 

Sets do not have sort order because sets have no concept of order. Arrays have a fixed order because the order of elements in an array is what defines an array. A set by contrast is defined by the uniqueness of each individual object in a set. An array can have many duplicates of the same element at different indexes but a set can never store the same object twice.

Core Data uses sets because it needs to know exactly which objects relate to one another. In most cases, any ordering e.g. alphabetical, numerical etc is needed only by the UI and plays no part in the actual modeling of the real-world objects, events or conditions the data model simulates. For example, if you had a model of Department<-->>Employee, all employees belonging to a particular department would comprise a set. You might need to sort employees by name, date of birth, hire date etc but that would be just for display and would have nothing to do with the relationship.

If you need to model any kind of arbitrary order, you need to add an attribute that holds an attribute that you can sort on as needed. This is not overhead because the order becomes part of the real-world objects, events or conditions simulated by the model.

TechZen