Viper827 Viper827 - 1 year ago 119
Swift Question

NSFetchedResultsController - Using a To-Many relationship as a NSSortDescriptor - Swift

I am having an issue with a

sortDescriptor. I have a To-Many relationship, that I want to use as a sortDescriptor. My problem is that this data is in a
. How can I use that in my sortDescriptor? When I ran it I got a:

"Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'to-many key not allowed here'"

Basically I have a DEVICE entity, and a TEST entity. I want to sort the devices using the latest date in the TEST entity. Judging by the lack of resources when using Google for this, I'm starting to wonder if it's even possible? If not what would be the easiest work around to accomplish this?

func fetchByFloor(){
let fetch = NSFetchRequest(entityName: "Device")
let sort = NSSortDescriptor(key: "estMessageFloor", ascending: false)
let sortTested = NSSortDescriptor(key: "latestTestDate", ascending: true)

let sortAddress = NSSortDescriptor(key: "estAddress", ascending: true)
let sortChanged = NSSortDescriptor(key: "deviceWasEdited", ascending: true)
fetch.sortDescriptors = [sort,sortTested, sortAddress]
fetch.fetchBatchSize = 20

let controller = NSFetchedResultsController(fetchRequest: fetch, managedObjectContext: ad.managedObjectContext, sectionNameKeyPath: "estMessageFloor", cacheName: nil)

controller.fetchRequest.predicate = devicePredicate
controller.delegate = self

fetchedResultsController = controller

navigationItem.title = "Building: \(currentBuilding)"


Answer Source

Not a true answer to my question but a work around I implemented that is working for now: I added another attribute in my DEVICE entity for lastestTestDate. Whenever this device gets a TEST entity added, I run a function that will sort my NSSet and return the first one. I then save that first result as my latestTestDate. I then use that in my sort descriptor to keep things in order. Seems like maybe a rig job way of getting things done but if a better solution can not be found, this seems to do the job for now.....