Complex sorting for core-data fetch request

天涯浪子 提交于 2020-01-04 02:35:07

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13044830/complex-sorting-for-core-data-fetch-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!