Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchedResultsController sections localized sorted

How could I use the NSFetchedResultsController with translated sort key and sectionKeyPath?

Problem: I have ID in the property "type" in the database like typeA, typeB, typeC,... and not the value directly because it should be localized. In English typeA=Bird, typeB=Cat, typeC=Dog in German it would be Vogel, Katze, Hund.

With a NSFetchedResultController with sort key and sectionKeyPath on "type" I receive the order and sections - typeA - typeB - typeC

Next I translate for display and everything is fine in English: - Bird - Cat - Dog

Now I switch to German and receive a wrong sort order - Vogel - Katze - Hund

because it still sorts by typeA, typeB, typeC

So I'm looking for a way to localize the sort for the NSFetchedResultsController.

I tried the transient property approach, but this doesn't work for the sort key because the sort key need to be in the entity.

I have no other idea. But I can't believe that's not possible to use NSFetchedResultsController on a derived attribute required for localization?

There are related discussions like Using custom sections with NSFetchedResultsController? but the difference is that the custom section names and the sort key have probably the same order. Not in my case and this is the main difference.

At the end I would need a sort order for the necessary NSSortDescriptor on a derived attribute, I guess. This sort order has also to serve for the sectionKeyPath.

Thanks for any hint.

like image 755
Gerd Avatar asked Apr 30 '10 12:04

Gerd


1 Answers

OK, not a nice solution but at the end it's working (because I have a defined limited set of records ca. 100):

On intializing the app:

  • I create an "order by" attribute in the managed object.
    • I check if the localization (and with it the sort order) changed since last time. If so:
    • I fetch all the records and sort it in an NSArray by localized names.
    • I write back the records in the store

For perfomance reason I only fetch and sort records according to a NSPredicate.

Than I can use all the existing code using the "order by" as sort key and section key path.

I know that I could use my ordered array as datasource for the table view, but I wanted to keep the existing code and use the methods of NSFetchedResultsController.

As a convenience of this I have full control over the sorting, that will fit my needs in future since I plan to build a more complex sort ordering (location based, higher probability of use of the records at the top, etc.)

However it's not an elegant solution.

like image 188
Gerd Avatar answered Sep 25 '22 16:09

Gerd