3

I have an NSEntity (Cloth) with an attribute (type) which is filled from a list of predefined NSString values i.e. Poncho‎, Jacket, Coat, Gown, Top, Suit, etc.

I want to fetch all the Cloth records such that the records are ordered based on a defined order for type. i.e. All the records for Poncho‎ are on top, then Jacket, then Coat, then Gown, then Top, then Suit, etc.

Poncho‎ …
Poncho‎ …
Poncho‎ …
Jacket … 
Jacket … 
Coat …
Coat …
Coat …
Gown …  
Gown …  
Top …
Top …
Top …
Top …
Suit …  
Suit … 

This order is not ascending or descending, rather it's custom. How can I fetch the Cloth records such that they are returned in this (defined) order?

2 Answers 2

8

A Core Data fetch request can only sort on attributes stored in the SQLite database (see Fetching Managed Objects and Fetch Predicates and Sort Descriptors in the "Core Data Programming Guide".)

You have the following options:

  • Fetch all objects and sort them afterwards with a custom sort descriptor. But this will not help if you are using a fetched results controller for a table view.

  • Store an additional integer attribute order in the Cloth entity and use that as sort key. This is perhaps the easiest one to implement, but you have some redundancy of course.

  • Instead of storing the type as string attribute, you could define another entity Type which has properties name and order, and a relationship type from Cloth to Type. In this case you could sort on the key path type.order.

2
5

The only way to implement a custom order is to introduce a new attribute of type NSNumber to keep track of the order.

[It seems that there is more text after the category string (Poncho, etc), so that you actually have many unique strings that all have to follow a custom order, only that they are grouped by first word.]

If you really want to separate this logic from the rest of the data, you can create a new entity ClothType with attributes name and sortOrder and have a relationship with your Cloth entity.

Another scheme is to multiply the sort attribute with, say, 10000 for every "primary" category and add 1 for each subsequent one of the same category.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.