Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting NSFetchedResultsController by Swift Computed Property on NSManagedObjectSubclass

I'm building an app using Swift with Core Data. At one point in my app, I want to have a UITableView show all the objects of a type currently in the Persistent Store. Currently, I'm retrieving them and showing them in the table view using an NSFetchedResultsController. I want the table view to be sorted by a 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 am setting up my NSFetchedResultsController's fetchRequest as follows:

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

Setting it up like this causes my app to crash with the following message in the log:

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

When I take out the first sort descriptor, my app runs just fine, but my table view isn't sorted exactly how I want it to be. How can I sort my table view based on a computed property of an NSManagedObject subclass in Swift?

like image 846
Michael Hulet Avatar asked May 08 '15 19:05

Michael Hulet


1 Answers

As was pointed out by Martin, you cannot sort on a computed property. Just update a new stored property of the club every time a shot is taken.

like image 197
Mundi Avatar answered Oct 21 '22 17:10

Mundi