How can I sort an NSFetchedResultsController by localized values?

57 views Asked by At

I'm almost completely done localizing my app to support multiple languages but I've run into a sorting problem I can't solve.

I have this entity:

import Foundation
import CoreData

extension Lift {
    @NSManaged var liftName: String
    @NSManaged var uuid: String
    @NSManaged var custom: Bool
    @NSManaged var liftEvent: NSSet?
}

and I have this fetch request which I use in several places that fetches all the Lift objects:

func fetchSelectableLifts() -> NSFetchedResultsController<NSFetchRequestResult> {
    var fetchedResultsController = NSFetchedResultsController<NSFetchRequestResult>()
    
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Lift")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "custom", ascending: true), NSSortDescriptor(key: "liftName", ascending: true)]
    
    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: #keyPath(Lift.custom), cacheName: nil)
    
    try! fetchedResultsController.performFetch()
    
    return fetchedResultsController
}

The problem is that I need to sort them by their localized liftName but I only store the names in English. It would impractical for me to store the names in multiple languages in Core Data.

Sort descriptor(s) must be specified when creating a NSFetchRequest<NSFetchRequestResult> and because the names are stored in English, it can only be sorted by the English names. The result is this:

enter image description here

Is it possible to sort an NSFetchRequest<NSFetchRequestResult> after it's been fetched?

EDIT 1

extension Lift {
    @objc
    var localizedLiftName: String {
        get { NSLocalizedString(liftName, tableName: "liftLogModel", comment: "") }
    }
}

and used it like this in my fetchRequest:

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Lift")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "custom", ascending: true), NSSortDescriptor(keyPath: \Lift.localizedLiftName, ascending: true)]

It crashes at runtime with this error: "Thread 1: "keypath localizedLiftName not found in entity Lift"

0

There are 0 answers