Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...