many key not allowed here
I have a many to many relationship between two entities; A
and B
.
I want to return an array of B.relationship
for every A
where B.relationship
's count is greater than 0 and sorted by B
's dateCreated
property.
This is the code I currently have which probably makes a little more sense.
let fetchRecentVariationsRequest = NSFetchRequest(entityName: "Variation")
fetchRecentVariationsRequest.predicate = NSPredicate(format: "ANY activities.@count > 0")
fetchRecentVariationsRequest.sortDescriptors = [NSSortDescriptor(key: "activities.dateCreated", ascending: true)]
When I run the request I get the following exception:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'
I understand why I'm getting the error but how I sort by a to many property for a sort descriptor in Core Data?
Edit
To be more clear, I'd like to fetch the 6 most recent Activity
entities sorted by their dateCreated
property (newest first).
Then I'd like to fetch all of the Variation
entities which are related to these fetched Activity
entities via the Activity
entity's variations
relationship.
You can't sort by the attribute of a to-many relationship, because it makes no sense. CoreData needs to decide which Variation to put first. Your sort descriptor says "use the value of dateCreated on the related Activities". But there are several Activities and so several different dateCreated values for each Variation. Which Activities' dateCreated should it use? The last? The first? The average?
But over and above that conceptual problem, CoreData will only allow you to use an attribute, or a to-one relationship, to sort by (at least for a fetch from the SQLite store). No transient properties; no computed properties. So if you want to use the dateCreated of the most recent related Activity, you will need to add an attribute to Variation which you update every time an Activity is added to the relationship.
EDIT
Given your update, I would fetch the most recent six Activities first:
fetchRecentActivitiesRequest = NSFetchRequest(entityName: "Activity")
fetchRecentActivitiesRequest.sortDescriptors = [NSSortDescriptor(key: "dateCreated", ascending: false)]
fetchRecentActivitiesRequest.fetchLimit = 6
// I recommend using the next line to fetch the related Variations in one go
fetchRecentActivitiesRequest.relationshipKeyPathsForPrefetching = ["variations"]
let recentActivities = try! context.executeFetchRequest(fetchRecentActivitiesRequest) as! [Activity]
and then use the variations
relationship to get the corresponding Variations
:
let nameSort = NSSortDescriptor(key: "name", ascending: true)
let recentVariations = recentActivities.flatMap() {
$0.variations!.sortedArrayUsingDescriptors([nameSort])
}
链接地址: http://www.djcxy.com/p/36154.html
上一篇: NSFetchedResultsController,按照TWO标准排序
下一篇: 许多钥匙不允许在这里