通过NSSortDescriptor通过对多关系计数获取CoreData [英] CoreData fetch with NSSortDescriptor by count of to-many relationship

查看:53
本文介绍了通过NSSortDescriptor通过对多关系计数获取CoreData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个具有以下关系的CoreData实体(人员,宠物):

I have 2 CoreData entities (Person, Pet) with the following relationship:

一个人可以有多个宠物。因此,Person-> Pet有一个多对多关系。

A Person can have multiple Pets. So, there is a To-Many relationship from Person->Pet.

我想获取所有Persons,并按照Pets的数量对它们进行分类宠物最多的是第一个,宠物最少的人是最后一个。

I want to fetch all Persons, sorted by the count of Pets that they have where the person with the most Pets is first, and the person with the fewest Pets is last.

在获取人员列表时,我尝试使用如下所示的NSSortDescriptor:

When fetching a list of Persons, I tried using an NSSortDescriptor like the following:

[NSSortDescriptor sortDescriptorWithKey:@"pets.count" ascending:NO]

我认为人上的 pets属性将允许我使用NSSet的count属性进行排序。 Core,CoreData抱怨此错误:

I thought that the "pets" property on a "person" would allow me to use the count property of NSSet to sort. Alas, CoreData complains with this error:

Fetch exception to-many key not allowed here

这是完全错误的方法吗?我应该如何通过CoreData抓取来做类似的事情?

Is this a completely wrong approach? How am I supposed to do something like this with a CoreData fetch?

在此先感谢您的帮助。

推荐答案

尝试使用集合运算符

[NSSortDescriptor sortDescriptorWithKey:@"pets.@count" ascending:NO]

这不能直接应用,但是(对于获取请求),您需要执行获取然后运行在结果数组上进行排序( sortedArrayUsingDescriptors:)。

This can't be applied directly though (to a fetch request), you need to execute the fetch and then run the sort on the result array (sortedArrayUsingDescriptors:).

如果要在获取时进行排序,则需要向拥有计数的实体添加(非暂时性)属性。

If you want to sort while fetching, you would need to add a (non-transient) attribute to the entity which holds the count number.

这篇关于通过NSSortDescriptor通过对多关系计数获取CoreData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆