If you are happy to change the CoreData model, you can create a new object to represent the categories. The Category object has three attributes: name (string), ascOrder (integer 16) and descOrder (integer 16). Then (as a one-time task) create four Category objects with values ββas follows:
name ascOrder descOrder
Replace the Category attribute of your object with the relation (to-one) to Category . The reverse attitude should be in many. Now, instead of setting the value of the attribute, for example, "Adult", you should set the relation to the Category object using the name "Adult". You can then configure FRC to sort objects by the category.ascOrder or category.descOrder key and specify the corresponding sectionNameKeyPath .
The result will be that your table will be grouped into sections and sorted correctly. However, since sectionNameKeyPath is set to ascOrder (or descOrder ), the name section property will be 1,2,3 or 4, not "Adult", "Child", etc. To fix this, in the tableView method titleForHeaderInSection or viewForHeaderInSection do not use:
let sectionInfo = self.fetchedResultsController.sections![section] let sectionName = sectionInfo.name
but instead, get the name by going to the first item in the section:
let sectionInfo = self.fetchedResultsController.sections![section] let firstItem = sectionInfo.objects![0] as! YourEntity let sectionName = firstItem.name
When using indexes, you may experience similar problems with index names.
If your application is already running, one of the drawbacks of this approach will be the need to transfer your data. I canβt remember if lightweight migration can handle attribute substitution with respect to a new object; I leave this to you for investigation.
source share