通过 NSManagedObjectSubclass 上的 Swift 计算属性对 NSFetchedResultsController 进行排序 [英] Sorting NSFetchedResultsController by Swift Computed Property on NSManagedObjectSubclass
问题描述
我正在使用 Swift 和 Core Data 构建一个应用程序.在我的应用程序中,我希望有一个 UITableView
显示当前在 Persistent Store 中的所有类型的对象.目前,我正在检索它们并使用 NSFetchedResultsController
在表视图中显示它们.我希望表视图按我的 NSManagedObject
子类的计算属性排序,如下所示:
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
}
}
}
在我的表视图控制器中,我正在设置我的 NSFetchedResultsController
的 fetchRequest
如下:
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>'
当我取出第一个排序描述符时,我的应用程序运行得很好,但我的表视图没有按照我想要的方式排序.如何根据 Swift 中 NSManagedObject
子类的计算属性对表视图进行排序?
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?
推荐答案
正如 Martin 所指出的,您不能对计算属性进行排序.每次击球时只需更新俱乐部的新存储属性.
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.
这篇关于通过 NSManagedObjectSubclass 上的 Swift 计算属性对 NSFetchedResultsController 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!