1
votes

Considering the following data model:

entity:                            entity:
- Order                            - Product
attribute:                         attribute: 
- date                             - productName
- orderName
relationship:                      relationship: 
- products  <<—- many-to-many —->> - orders

I want to display all products sorted by order date, and in case of many orders associated to one product, by oldest order date. All products without orders should be displayed last.

I am lost how I can do this using NSSortDescriptor. Apparently, I could fetch all product data, convert order (which is of type NSSet) to determine the oldest date, and then to sort products by order date. Although I was unable to get this working in this way, it will also not work with NSFetchedResultsController for displaying the products in a UITableView and is probably very very very non-efficient.

How could I do this sorting in somewhat more efficient manner, as it would also be possible using SQL? And if required, how should NSFetchedResultsController be modified? Something like the following code:

let fetchRequest = NSFetchRequest(entityName: “Product”)
let sortDescriptor1 = NSSortDescriptor(key: “product.order.date … ????”, descending: 
let sortDescriptor2 = NSSortDescriptor(key: “product WITHOUT order … ????”, descending: 

fetchRequest.predicate = NSPredicate(format: “productName contains[cd] %@", “A”)
fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2]

let fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

Fetching data in cellForRowAtIndexPath

let product = fetchedResultController.objectAtIndexPath(indexPath) as! Product
1

1 Answers

0
votes

It appears that it is just not possible to sort an Entity based on attributes (of type NSSet) of another Entity. The reason is that FRC only watches one Entity a time, preventing more complex sorting.

Currently, I switched from Core Data to Realm and the problem was easily solved (among several other problems where I could rid of).