简体   繁体   中英

iPhone: NSSet keep sort order

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.

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 eg 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.

If you don't want to sort them you can add a property (eg 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 
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM