Sort NSFetchedResultsController by quick computed property in NSManagedObjectSubclass

I am building an application using Swift with basic data. At some point in my application, I want the UITableView show all objects of the type currently in the Persistent Store. I am currently NSFetchedResultsController them and showing them as a table using NSFetchedResultsController . I want the table view to be sorted by the computed property of my NSManagedObject subclass, which looks like this:

 class MHClub: NSManagedObject{ @NSManaged var name: String @NSManaged var shots: NSSet var averageDistance: Int{ get{ if shots.count > 0{ var total = 0 for shot in shots{ total += (shot as! MHShot).distance.integerValue } return total / shots.count } else{ return 0 } } } 

In my table view controller, I configure my NSFetchedResultsController fetchRequest as follows:

 let request = NSFetchRequest(entityName: "MHClub") request.sortDescriptors = [NSSortDescriptor(key: "averageDistance", ascending: true), NSSortDescriptor(key: "name", ascending: true)] 

Setting this type will crash my application with the following log message:

 'NSInvalidArgumentException', reason: 'keypath averageDistance not found in entity <NSSQLEntity MHClub id=1>' 

When I take out the first sort descriptor, my application works fine, but my table view is not sorted exactly as I want. How can I sort the table view based on the computed property of the NSManagedObject subclass in Swift?

+6
source share
1 answer

As Martin pointed out, you cannot sort by computed property. Just update the club’s new stored property every time it is rented.

+3
source

Source: https://habr.com/ru/post/986842/


All Articles