Change sort order regardless of NameKeyPath section in NSFetchedResultsController

I am using NSFetchedResultsController to group by section in which sectionNameKeyPath matches the category.

My categories: Adult, Child, Vision, None.

Ascending sort: Adult, Child, No, Vision

Sort Descending: Vision, None, Child, Adult

I want no category to come, finally, always regardless of the sort order.

Increasing desired view: Adult, Child, Vision, None

Descending Desired Type: Vision, Child, Adult, None

The code used is as follows:

 let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedOC, sectionNameKeyPath: "category", cacheName: nil) 
+5
source share
2 answers

I think since you are saving the category, since the value of String and String can only be sorted in alphabetical order. Is it possible if you can create a numeric field in a database? And save the numerical value, for example, Adult = 1, Child = 2, Vision = 3, No = 4, you can easily sort and sort the data in ascending or descending order. Hope this helps you.

0
source

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 ==== ======== ========= Adult 1 3 Child 2 2 Vision 3 1 None 4 4 

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.

0
source

Source: https://habr.com/ru/post/1272937/


All Articles