Search code examples
iosswiftcore-datansfetchedresultscontroller

Sorting NSFetchedResultsController alphabetically and in sections


I am using an NSFetchedResultsController to manage my tableView, I am trying to sort the entity into sections alphabetically, similar to how your contacts app would look. I am getting this error when trying to run my code: the entity Exercise is not key value coding-compliant for the key "nameFirstChar".'

nameFirstChar is a computed property in the Exercise subclass as seen here:

var nameFirstChar: String {
        get {
            if let char = self.name?.first {
                return String(char)
            }
            return "#"
        }
    }

this is how I set up my NSFetchedResultsController:

let fetchRequest:NSFetchRequest<Exercise> = Exercise.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: DataController.shared.context, sectionNameKeyPath: "nameFirstChar", cacheName: nil)

Not sure what is causing this problem, anyone have any insight?


Solution

  • You need to ensure that you mark your computed property as @objc, otherwise it is not visible to the Core Data framework (which is written in Objective C).

    @objc var nameFirstChar: String {
        return String(self.lastName?.first ?? "#").uppercased()
    }