可能具有核心数据对“许多”进行排序。在抓取请求期间是否为“多对”关系的一部分? [英] Is it possible to have Core Data sort the "many" part of a To-Many relationship during a fetch request?

查看:169
本文介绍了可能具有核心数据对“许多”进行排序。在抓取请求期间是否为“多对”关系的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Core Data缓存大量信息,并且在我的托管对象中设置了一对多关系。自然,我使用NSFetchRequest来获取该关系的奇异边的数组。但是,我使用关系的许多一侧填充一个UITableView,当我拉取数据时,我希望它按字母顺序排序。

I'm using Core Data to cache a decent amount of information, and I have a To-Many relationship set up among my managed objects. Naturally I use an NSFetchRequest to fetch an array of the singular side of that relationship. However, I populate a UITableView using the the "many" side of the relationship, and I'd like it to be sorted alphabetically when I pull the data.

如果我不清楚,这里是一个例子:

If I'm not being clear, here's an example:

employee和boss都是NSManagedObjects在一对多的关系 - 每个老板有很多员工,只有一个boss。在检索一个boss数组之后,我推一个包含一个雇员列表的UITableViewController。我想让员工在NSFetchRequest期间预先排序,使显示它们更容易。这是可能的,我该怎么做呢?

"employee" and "boss" are both NSManagedObjects in a To-Many relationship - each boss has many employees, but employees only have one boss. After retrieving an array of bosses, I push a UITableViewController containing a list of employees. I'd like the employees to be pre-sorted during the NSFetchRequest to make displaying them easier. Is this possible, and how would I go about doing it?

推荐答案

为什么不从相反?我假设你已经知道你感兴趣的老板的唯一id,所以你可以建立一个这样的谓词:

Why not fetch from the reverse? I assume you already know the unique id of the boss you're interested in, so you could build a predicate like this one:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"boss.bossId == %K", bossId];
NSFetchRequest *req = [[NSFetchRequest alloc] init];
[req setEntity:employeeEntity];
[req setPredicate:pred];

这应该取出具有匹配的bossId的任何员工,然后可以向该fetch添加排序描述符请求按字母顺序排序。

That should fetch out any employee with a matching bossId, you can then add a sort descriptor to that fetch request to sort alphabetically.

或者,您可以抓取在当前实现中提取的NSManagedObject实例数组,并使用排序描述符对它们排序是属性name):

Alternatively you could grab the array of NSManagedObject instances that you fetch out in your current implementation, and sort them using a sort descriptor (assumes your employees name is at the property "name"):

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YESorNO];
NSArray *sorted = [entities sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

现在使用已排序填充您的tableview。

Now populate your tableview using "sorted".

注意:
我有点困惑,为什么你不使用NSFetchedResultsController为此,因为它会照顾你的切片。

Note: I'm a little confused about why you're not using an NSFetchedResultsController for this, as it would take care of sectioning for you as well.

这篇关于可能具有核心数据对“许多”进行排序。在抓取请求期间是否为“多对”关系的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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